很难将另一个LINQ创建的实体更新为SQL上下文 [英] Hard to update an Entity created by another LINQ to SQL context

查看:50
本文介绍了很难将另一个LINQ创建的实体更新为SQL上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这整天困扰着我.

Why this keep bugging me all day.

我有一个带有多个引用的实体,该实体是从上下文中获取的,然后我将其丢弃. 进行一些更改,然后尝试SubmitChanges().在不使用.Attach()的情况下调用SubmitChanges()时,似乎根本不执行任何操作.使用.Attach()时,出现异常:

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 :

已尝试附加或添加一个不是新的实体,可能是从另一个DataContext加载的.不支持.

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.

有什么想法吗?

推荐答案

L2S对于更新来自不同数据库上下文的实体非常挑剔.实际上,除非您先将其与所来自的上下文分离",否则您将无法做到这一点.分离实体有两种不同的方法.其中之一如下所示.该代码将在您的实体类中.

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;
}

除此之外,您还可以使用基于WCF的序列化序列化您的实体.像这样:

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);
        }
    }

这篇关于很难将另一个LINQ创建的实体更新为SQL上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆