简体   繁体   English

如何判断Linq对象是否已附加到数据上下文?

[英]How to tell if a Linq object has been attached to a data context?

Using Linq-to-Sql: 使用Linq-to-Sql:

MyClass obj;
...
// need to delete this object
dataContext.GetTable(obj.GetType()).DeleteOnSubmit(obj);

BUT

I don't know whether or not obj has been attached to the data context. 我不知道obj是否已附加到数据上下文中。 And if it hasn't, that last call to DeleteOnSubmit throws an exception. 如果没有,最后一次调用DeleteOnSubmit会抛出异常。

There has to be an easy way of telling whether obj is attached to dataContext - but I can't see anything obvious. 必须有一种简单的方法来判断obj是否附加到dataContext - 但我看不到任何明显的东西。

How do you do it? 你怎么做呢?

While you may want to take a look at your design, since this sort of thing should be something that you can figure out deterministically, it's possible to do. 虽然你可能想看看你的设计,因为这种东西应该是你可以确定性地找出的东西,但它可以做到。

Unfortunately, the exact call to determine if the object is attached (or, in L2S's internal nomenclature, "tracked") requires that you call Context.Services.ChangeTracker.GetTrackedObject , which is internal . 不幸的是,确定对象是否附加的确切调用(或者,在L2S的内部命名法中,“跟踪”)要求您调用Context.Services.ChangeTracker.GetTrackedObject ,这是internal The closest thing I can see is calling Table.GetOriginalEntityState , passing in the entity in question. 我能看到的最接近的事情是调用Table.GetOriginalEntityState ,传入相关实体。 If the return value is null , then the object is untracked (unattached). 如果返回值为null ,则对象未跟踪(未附加)。 If the return value is non- null , then the object is tracked (attached). 如果返回值为非null ,则跟踪(附加)对象。

Note that I haven't actually tested this, but looking at the code in Reflector gives me the impression that this should work for you. 请注意,我实际上没有对此进行过测试,但查看Reflector中的代码会让我觉得这应该适合您。

Link2SQL, I assume? Link2SQL,我假设? This should be apparent from your code. 这应该从您的代码中显而易见。 Do you really need to query the state dynamically at runtime? 您真的需要在运行时动态查询状态吗? obj is only attached if you obtained it from your dataContext. 只有从dataContext获取obj时才会附加obj。

I asked a similar question a while ago . 我刚才问了一个类似的问题 Maybe Robert Harvey's comments are helpful to you. 也许Robert Harvey的评论对你很有帮助。

One way you can tell if an object is attached to a data context is by looking at the PropertyChanging and PropertyChanged events. 通过查看PropertyChanging和PropertyChanged事件,可以判断对象是否附加到数据上下文的一种方法。

I have a method on my entities to detach them as follows: 我的实体上有一个方法可以将它们分离如下:


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

So, if these two properties are not null, the object is attached. 因此,如果这两个属性不为null,则附加对象。

Randy 兰迪

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM