I just upgraded one of my application's methods to use compiled queries (not sure if this is relevant). Now I'm getting contradicting error messages when I run the code.
This is my method:
MyClass existing = Queries.MyStaticCompiledQuery(MyRequestScopedDataContext, param1, param2).SingleOrDefault();
if (existing != null)
{
MyRequestScopedDataContext.MyClasses.DeleteOnSubmit(existing);
}
When I run it I get this message:
Cannot remove an entity that has not
been attached.
Note that the compiled query and the DeleteOnSubmit reference the same DataContext. Still I figured I'd humor the application and add an attach command before the DeleteOnSubmit, like so:
MyClass existing = Queries.MyStaticCompiledQuery(MyRequestScopedDataContext, param1, param2).SingleOrDefault();
if (existing != null)
{
MyRequestScopedDataContext.MyClasses.Attach(existing);
MyRequestScopedDataContext.MyClasses.DeleteOnSubmit(existing);
}
BUT… When I run this code, I get a completely different contradictory error message:
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.
I'm at a complete loss…
Does anyone else have some insight as to why I can't delete a record via the same DataContext I retrieved it from?
Best Answer
Well, a static data-context already sounds like a potential issue (in particular threading, but also stale objects, and disposal). My immediate thought is: is object tracking enabled? Not sure if it needs to be, but certainly one to consider.