Attached entity
Hi all,
How can I determine that my entity is already attached to the DataContext?
For example when I use cache, I need to attach my entity object for update or load some data. But when I attach the entity second time I get
InvalidOperationException: Cannot attach an entity that already exists
[308 byte] By [
Vadzim] at [2008-1-8]
Hello,
I thought I had replied to this post, but I think IE crashed.
You might want to have a look at this post:
http://west-wind.com/weblog/posts/134095.aspx
Hope this helps, if you have any more questions then please let us know.
Regards
Ben
Hi Ben,
Thank you, your post was very helpful, but it is still unclear for me how to use LINQ with N-tier applications (including caching).
And it seems that there is no way to determine that my entity is already attached to the DataContext.
Best regards
I don't think there's a way to tell whether an entity is already attached.
But what scenario do you have where you wouldn't know?
The other issue might be how you are attaching the entity. Most likely you're using two entities to Attach() (ie. using existing state) and if you loaded that existing state out of the same context you are in fact duplicating the instance.
This is a followup to the first post mentioned earlier.
http://www.west-wind.com/weblog/posts/135659.aspx
and it might help in your scenario to reattach the context.
If you really have to deal with this issue I suppose you can try to attach and capture the exception that occurs if the entity is already tracked.