开发者

Hard to update an Entity created by another LINQ to SQL context

开发者 https://www.devze.com 2022-12-22 01:38 出处:网络
Why this keep bugging me all day. I have an entity with several references where i get from a context which I then Dispose.

Why this keep bugging me all day.

I have an entity with several references where i get from a context which I then Dispose. Do some Changes and try to SubmitChanges(). While calling SubmitChanges() without .Attach() seems to simply do nothing. When using .Attach() I get the Exception :

An attempt has been made to Attach or Add an entity that is not new, perhaps having been loaded from a开发者_JAVA百科nother DataContext. This is not supported.

Any ideas?


L2S is very picky about updating an entity that came from a different DB context. In fact, you cannot do it unless you 'detach' it first from the context it came from. There are a couple different ways of detaching an entity. One of them is shown below. This code would be in your entity class.

public virtual void Detach()
{
    PropertyChanging = null;
    PropertyChanged = null;
}

In addition to this, you can also serialize your entity using WCF based serialization. Something like this:

    object ICloneable.Clone()
    {
        var serializer = new DataContractSerializer(GetType());
        using (var ms = new System.IO.MemoryStream())
        {
            serializer.WriteObject(ms, this);
            ms.Position = 0;
            return serializer.ReadObject(ms);
        }
    }
0

精彩评论

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