Entity Framework: What negatives can I solve without getting rid of my object context?

EDIT: Duplicate Should the Entity Framework context use the Statement in use?

I've been pondering this idea for a while, pondering what bad things can happen by not properly disposing of my object's context and letting it die with the GC. I would normally avoid this, but there is a good reason for this.

We are using partial classes. In these partial classes, we find properties that refer to FK objects. For example, let's say I have a Customer class with a CustomerType FK object. In the class, I would expand the CustomerTypeName property, which does the following:

public string CustomerTypeName {
  get {
     if (CustomerType == null) {
         CustomerTypeReference.Load() 
     }

     return CustomerType.CustomerTypeName;
  }
}

      

This is very useful if the original request did not do .Include ("CustomerType").

However, if I use the context, the specified property no longer works. So ... I think this leads to two questions:

1) If I never have direct control over the context, what negatives will I see, if any?
2) Is there any other way to perform lazy loading in the above scenario and still get rid of the context?

0


a source to share


3 answers


Well ObjectContext that stay indefinitely are fine as long as you don't keep loading / adding many new objects.

Every object that is loaded or added will always be tracked by the ObjectContext until it is removed, so if you never dispose of and you keep tracking more objects, it will just get bigger and bigger.

One option you might want to look at is to use some utility method to access a known context or create a temporary context.

The key to this is to use EntityReference.EntityKey and make sure both objects are detached.

i.e.

this.CustomerType = Utility.GetDetachedObjectByKey<Customer>(
       this.CustomerTypeReference.EntityKey);

      



The main implementation of GetDetachedObjectByKey looks like this:

public static T GetDetachedObjectByKey<T>(EntityKey key) 
     where T: EntityObject
{
    using (MyContext ctx = new MyContext())
    {
        T t = ctx.GetObjectByKey(key) as T;
        ctx.Detach(t);
        return t;
    }
}

      

This will only work if the target of the source object is also disabled. You can experiment with where the context used by this method comes from.

Hope it helps

Alex

+2


a source


In my answer to LINQ to SQL - where does your DataContext live? 'we have as owner the DataContext for the life of the page, and it is the page that correctly deletes the DataContext when the page itself is deleted.



As @Chu points out, it's a little messy, but if you are going to use what is possibly a data transfer object directly in the UI, then your UI should control the lifetime of the DataContext.

+3


a source


Why not keep context around the length of the screen?

0


a source







All Articles