views:

233

answers:

1

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?

A: 

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.

Marc Gravell
It's an asp.net application, I use the static reference so that only one instance of the DataContext is created per request. I debugged to make sure this was true in this instance, and that seems to be the case.
Antilogic
biiiig no; "static" != "per request". static = "every call shares this one". Be very cautious of static in ASP.NET. You probably won't notice much pain on a dev machine, but on a server? It scales to 1 user, at least.
Marc Gravell
It's not just static it's served from a specialized class that ensures only one context is created per request. I've thoroughly tested to make sure the DataContext is only initialized once for every request and especially this unit of work.
Antilogic
The DataContext is acctually stored in the HttpContext.Items Dictionary. So I guess it's not really static, sorry if that was a red haring. I changed the sample code to reflect this more accurately
Antilogic
Ah, OK; I thought it better (safest) to assume the worst ;-p
Marc Gravell