Hard to update an Entity created by another LINQ t

2019-08-22 06:16发布

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 another DataContext. This is not supported.

Any ideas?

标签: linq-to-sql
1条回答
老娘就宠你
2楼-- · 2019-08-22 06:39

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);
        }
    }
查看更多
登录 后发表回答