Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to Serialize a LINQ object?

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?

like image 276
Mykroft Avatar asked Dec 01 '08 21:12

Mykroft


People also ask

Can we serialize struct in C#?

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.

Can you serialize a struct?

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.

Can you serialize a string?

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.


1 Answers

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.

like image 68
Marc Gravell Avatar answered Sep 18 '22 12:09

Marc Gravell