Raheel Khan
Raheel Khan

Reputation: 14787

Determine if the context of an entity proxy has been disposed

In a EF 6 project, I am writing validation functions for entities. some are static while others are instance methods of the entities themselves.

Ignoring whether this is bad practice or not, I'd like to check whether the entities were created using a context and if so, whether they are still attached.

Please note that these functions do NOT have access to the context object, just the entity classes.

As an example, a method validates Department entity and cascades validation to all associated Department.Employee instances.

So the question, is it possible to detect the above scenarios without access to a DbContext instance? If not, how can we best validate entire hierarchies irrespective of how they were created.

var result = true;
var departments = ???; // Constructed manually or through a DbContext instance.

foreach (var department in departments)
{
    result &= department.Validate();

    foreach (var employee in department.Employees)
    {
        result &= employee.Validate();
    }
}

EDIT: Please note that this is for a desktop application that cannot have long-running DbContext instances. they are almost always disposed immediately after retrieving data. Re-querying the database does not seem a viable option for validation since it is triggered by trivial user input and would slow down the entire user experience.

Upvotes: 2

Views: 1975

Answers (1)

Kit
Kit

Reputation: 21739

From your question

Please note that these functions do NOT have access to the context object, just the entity classes.

two solutions come to mind, none really palatable:

  1. Build your own tracker and make it available to these methods somehow.
  2. Add something to your entities, for example a WasLoaded property that gets set when you query your context. That WasLoaded could be set by either
    1. Writing an EF interceptor that sets it.
    2. Adding an artificial bit column with all values set to 1. Then map that to the property; the property will be false if you constructed it outside of the context, true if loaded from the context.

The tracker seems to be the cleanest because it doesn't pollute your model. The interceptor is a decent alternative if you're not concerned about your model.

And while it doesn't answer your question directly, you could avoid the use of proxies, in which case your validation works the same way regardless because you have your model in memory. There's the usual trade-offs to consider though.

I'm not sure how you'd detect the last scenario. I suppose you could have your tracker track more than the entities... have it also track the context's state.

Upvotes: 1

Related Questions