开发者

Linq to Sql - Unable to make a deep copy of an L2S entity

I am trying to make a deep copy of a L2S entity using the code below. I have the Serialization Mode of the .DBML set to Unidirectional. However, when I attempt to make a deep copy of an L2S entity, using the DeepCopy method shown below, I get an error saying the object isn't marked as serializable. Anyone know why?

public static T DeepCopy<T>(T obj)
{
    object result = null;

    using (var ms = new MemoryStream())
    {
        var formatter = new BinaryFormatter();
        formatter.Serialize(ms, obj);
        ms.Position = 0;

        result = (T)formatter.Deserialize(ms);
        ms.Clo开发者_如何学Gose();
    }

    return (T)result;
}

One of my L2S class definitions looks as follows:

[global::System.Data.Linq.Mapping.TableAttribute(Name="Polar.Recipe")]
[global::System.Runtime.Serialization.DataContractAttribute()]
public partial class RecipeRecord : INotifyPropertyChanging, INotifyPropertyChanged


DataContract attribute is required by DataContractSerializer but wont' work with other serializers like BinarySerializer, ViewStateSerializer and other serializers. In order to make them work You have to use Serializable attribute to apply to them. Now how to make that easy...

When I want to extend my Linq2Sql entities I usually abuse the fact that they are ALL partial classes. So I create file Linq2SqlExtensions.cs

public partial class LinqEntity
{
//extensions go here
}

and other extensions (like for example data context extensions). Now if You have many entities You can write a small program (even in powershell) to extract all class names out of Your Linq2Sql namespace/assembly (I pray You have them in another assembly) and create this file for You and automatically update it for You everytime YOu run it from VisualStudio Command line (or msBuild script).

something like

var entities = Assembly.Load("MyLinqAssembly").GetTypes().Where(p=> p.IsDefined(typeof(TableAttribute), true));
WriteEntityCsFile(entities);


Did you try adding Serializable attribute to your entity classes? It's possible that DataContract attribute allows serialization only through WCF and other communication services, and not using BinaryFormatter.

Alternatively, try using DataContractSerializer instead BinaryFormatter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜