I'd like to serialize some LINQ generated objects and store them in a table as a binary field (Never you mind why). I'd like to be able to write some code that looks something like this:
SerialTestDataContext db = new SerialTestDataContext();
relation_table row = db.relation_tables.First();
MemoryStream memStream = new MemoryStream();
BinaryFormatter bin = new BinaryFormatter();
bin.Serialize(memStream, row);
Console.WriteLine("Serilized successfully");
TestTable tt = new testTable();
tt.data = new System.Data.Linq.Binary(memStream.ToArray());
db.testTables.InsertOnSubmit(tt);
db.SubmitChanges();
Console.WriteLine("Inserted successfully");
Currently that fails even though I've marked the generated classes as [Serializable] because one of the LINQ inherited classes is not. Is it even possible to do this?
Yes, you can. I just did so with the following code. [Serializable] public struct TestStruct { public int Value1 { get; set; } public int Value2 { get; set; } public string Value3 { get; set; } public double Value4 { get; set; } } TestStruct s1 = new TestStruct(); s1.
The struct and XML are corresponding. If you want to serialize the struct in your code, you could use the following code. The serialize is according to the struct of the class, hence it is impossible to serialize part of the struct. Here is the output.
Serialization : Scan each element in a string, calculate its length and append it with a string and a element separator or deliminator (that deliminator should not be present in the string). We append the length of the string so that we know the length of each element.
With linq-to-sql (from tags), then yes: you can mark the dmbl as serializable, which uses the [DataContract]/[DataMember] approach. You do this by setting the "Serialization Mode" to "Unidirectional" in the designer, or you can do it in the dbml itself:
<Database ... Serialization="Unidirectional">...
You can then use DataContractSerializer or NetDataContractSerializer to write this (as xml or binary respectively). If you need something portable (i.e. not MS/.NET specific), then protobuf-net will serialize data-contracts using the "protocol buffers" spec.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With