如何深入了解此Linq to SQL错误? [英] How do I get to the bottom of this Linq to SQL error?

查看:51
本文介绍了如何深入了解此Linq to SQL错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试附加或 添加一个不是新的实体,也许 从另一个加载 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.

我已经与Linq to SQL合作了一段时间,我相信我知道它的局限性,并且在编写新代码时会遵循规则.但是获取此异常令人沮丧,因为没有迹象表明哪个对象引起了违规.在具有多个DC的复杂数据操作方案中,我只能想到反复试验才能缩小可能的罪魁祸首.有办法找到更多吗?

Having worked with Linq to SQL for some time, I believe that I know about its limitations and that I follow the rules when I write new code. But it is frustrating to get this exception, as there is no indication of which object caused the violation. In complex data manipulation scenarios with multiple DCs, I can only think of trial-and-error to narrow down the possible culprits. Is there a way to find out more?

推荐答案

如果将对象附加到DataContext,则必须由您使用new运算符创建了该对象.如果从DataContext中读取对象,则必须将其保存到相同的DataContext中.

If you attach an object to your DataContext, it must have been created by you using the new operator. If you read the object from a DataContext, you must save it to the same DataContext.

为减轻此类问题,我始终使用单个DataContext,并且在工作单元"的基础上进行所有操作.

To alleviate these kinds of problems, I always use a single DataContext, and I do everything on a "unit of work" basis.

通常来说,这意味着在任何给定的时间,我都在读取所需的记录,对这些记录执行工作,并使用单个DataContext在单个工作单元中保存更改.由于它是一个工作单元,因此不会渗入其他DataContext对象.

Generally speaking, that means that, at any given time, I am reading the records I need, performing work on those records, and saving changes, all in a single unit of work, using a single DataContext. Since it is a unit of work, it doesn't bleed over into other DataContext objects.

如果Linq to SQL在此方面与您作斗争,我将检查您的体系结构,看看您的操作方式是否是最佳的,尤其是在发现难以识别导致错误的对象的情况下.通常,很难在DataContext之间共享对象.您可以做到这一点(使用"attach"和"detach"之类的东西),但是这很麻烦.

If Linq to SQL is fighting you on this, I would examine your architecture and see if the way you are doing it is optimal, especially if you are finding it difficult to identify the object causing the error. In general it is difficult to share objects between DataContexts. You can do it (using things like "attach" and "detach"), but it's a pain in the ass.

这篇关于如何深入了解此Linq to SQL错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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