开发者

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

Using 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. And if it hasn't, that last call to DeleteOnSubmit throws an exception.

There has to be an easy way of telling whether obj is attached to dataContext - but I can't see anything obvious.

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. The closest thing I can see is calling Table.GetOriginalEntityState, passing in the entity in question. If the return value is null, then the object is untracked (unattached). If the return value is non-null, then the object is tracked (attached).

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.


Link2SQL, I assume? 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.

I asked a similar question a while ago. Maybe Robert Harvey's comments are helpful to you.


One way you can tell if an object is attached to a data context is by looking at the PropertyChanging and PropertyChanged events.

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.

Randy

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜