Can't delete record via the datacontext it was retrieved from

Posted by Antilogic on Stack Overflow See other posts from Stack Overflow or by Antilogic
Published on 2009-09-17T15:10:01Z Indexed on 2010/05/23 13:00 UTC
Read the original article Hit count: 210

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET