1

I have a class generated by Linq2Sql:

public partial class BuyerOrder : INotifyPropertyChanging, INotifyPropertyChanged

I want to clone object of this class, like it's done in this post. For this purpose I define the partial class in not generated file, which I mark as serializable:

[Serializable]
public partial class BuyerOrder    

But when I'm calling

formatter.Serialize(stream, source);

I'm getting an exception, saying that this class is not marked as serializable. What am I doing wrong?

Community
  • 1
  • 1
valerii.sverdlik
  • 559
  • 4
  • 18
  • 1
    My guess is that the serializer is trying to follow all public properties of your class and if your class has references to other entities, these are NOT marked as serializable. – Wiktor Zychla Aug 21 '12 at 18:31
  • yes, but in this case exception would specify an exact class which is not serialized – valerii.sverdlik Aug 21 '12 at 18:34
  • @valerii.sverdlik it is almost certainly talking about one of the private implementation detail classes, not `BuyerOrder` itself. Most likely, the data-context – Marc Gravell Aug 21 '12 at 18:42

2 Answers2

2

If you want to serialize a LINQ-to-SQL type, then tell the code-gen to emit serializable data. You can do this in the DBML, or more simply in the designer - just set the serialization mode to unidirectional (this is the @Serialization attribute on the root <Database> element in the DBML).

This will generate attribute markers suitable for use with DataContractSerializer; LINQ-to-SQL is designed to be serializable with DataContractSerializer. It is not designed to be serializable with BinaryFormatter.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
0

Every class derived from BuyerOrder must also be decorated as [Serializable], as well as all objects that the serializing instance holds a reference to (unless decorated as NonSerializable).

The exception should tell you the type that is missing the serializable attribute. If you can not or do not want to decorate all the classes you will need to get a little more creative.

-- The other possibility --

One option is to use the technique described in Implementing a generic deep-clone for C# objects. Since this can be done entirely in memory and without a binary formatter it will perform many times faster than serialization based cloning.

The source code is located at http://csharptest.net/browse/src/Library/Cloning

It only takes two lines of code:

using (ObjectCloner cloner = new SerializerClone())
    fooCopy = cloner.Clone(foo);
csharptest.net
  • 62,602
  • 11
  • 71
  • 89