we can easily serialize class to flat file but if i want to serialize class to database then how could i do it and if it is possible then how can i deserialize data from db to class. please give a sample code in c#.
thanks
we can easily serialize class to flat file but if i want to serialize class to database then how could i do it and if it is possible then how can i deserialize data from db to class. please give a sample code in c#.
thanks
Like other said at already, you can use binary serialization to get the Byte[] array in a memory stream and then create a column in database of type Blob / image to store the the byte array.
Then while reading back, you just read the value of the column in the stream back by using technique called deserialization
Serialization
BinaryFormatter bf = new BinaryFormatter();
List<SearchFilterDetails> _list = QueryFilterDetails.ToList<SearchFilterDetails>();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, _list);
return ms.GetBuffer();
}
Deserialization
private void DeSerilizeQueryFilters(byte[] items)
{
BinaryFormatter bf = new BinaryFormatter();
List<SearchFilterDetails> _list = new List<SearchFilterDetails>();
try
{
using (MemoryStream ms = new MemoryStream())
{
ms.Write(items, 0, items.Length);
ms.Position = 0;
_list = bf.Deserialize(ms) as List<SearchFilterDetails>;
}
foreach (SearchFilterDetails mobj in _list)
{
QueryFilterDetails.Add(mobj);
}
}
catch (Exception ex)
{
}
}
Thomas, what kind of data access logic are you using in your application?
If you are looking for a way to interact with the database and store/retrieve objects from it, you could also have a look at Entity Framework or NHibernate, such ORMs allow you to focus on what really matters in your application and not on the way objects/entities are loaded or saved.
You can serialize a class (out of the box) to binary form or to XML.
In the first case you get a byte[], and in the second you get a simple string.
If you want to persist that in the database, just treat it as any other byte array or string (or XML, if your database natively supports that) that need to be sent to the database.
Using binary serialization to BLOB column, or using XML\Data contact\net Data contact to XML column.
Edit: Binary example already given by @Saurabh. Data contract example provided by Peter Ritchie's blog.