Search code examples
entity-frameworkactiverecorddependency-injectionbusiness-logicanemic-domain-model

ObjectContext aware entity in EF to avoid Anemic Domain Model


In Entity Framework, is it possible to make the framework inject the DbContext into each object (entity) that is attached to or retrieved from the Context?

I'm an NHibernate guy and I know it is possible in NH, -- sorry if it is a stupid question in EF world.

Essentially, I want some of my entities to have a property of type DbContext that will get set to the instance of the context by the framework itself, whenever I associate the entity with the context. Ideally such classes will be marked with IContextAware marker interface or something like that.

The reason I want to do this is (=goal), I want to avoid Anemic Domain Model anti-pattern this time around. I figured if I have ObjectContext injected into entities, they will be able to access DB, thereby allowing me to implement queries and more complex logic right inside domain classes themselves. If you know other ways to accomplish my goal (esp. in context of web app) please do, but please try to avoid answers like "you shouldn't do this because". Thanks!!!


Solution

  • You shouldn't do this because you want to keep persistence concerns out of your domain objects =)

    But if you MUST, you can hook into the ObjectMaterialized event fired by ObjectContext. In CTP5, you need to cast your DbContext like so in the constructor for your DbContext:

    ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += 
        this.ObjectContext_OnObjectMaterialized;
    

    Then implement your function ObjectContext_OnObjectMaterialized(object sender, ObjectMaterializedEventArgs e). Via the EventArgs, you will be able to access your object, which has just been materialized. From there, you can set your POCO's ObjectContext/DbContext property, which has to be either public or internal.