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?
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:
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.