0

I create a new System.Data.Objects.ObjectContext (my EF model) every time a DAL method is called:

Public void DoSomeDataManipulation()
{
    using (MyModel myModel = new MyModel(connectionString))
        myModel.AddRecord(someParametersHere);
}

DoSomeDataManipulation() is called frequently (also many other methods). I have tried a static version of myModel but EF produces many concurrency errors on high load.

Currently I'm curious if this approach can lead a Large Object Heap or not and if it is the best practice for calling mapped EF methods.

Xaqron
  • 26,135
  • 39
  • 130
  • 194

1 Answers1

0

Using static context is a bad practice - you have found that it doesn't work in concurrent scenario (because context is not thread safe) but it also has other problems.

You should use a new instance of the context for each unit of work. Is adding single record unit of work (business operation / transaction)? In such case you are using it right. If your unit of work is adding multiple records or any other more complicated scenario where you insert / update / delete several entities you should use one context instance for the whole operation.

Using new context for the operation should not cause performance problems. Context internally uses some mapping description which is shared anyway. Problems with large heap can happen but that will not make any difference when using static context.

Large heap can happen due to memory leaks caused most often by POCO proxies (either tracking or lazy loading). If you load entity from the context and then dispose the context without detaching the entity it will still hold reference to the context and context will hold references to all attached entities = if the main entity is still referenced neither object context or anything it references can be garbage collected. In the same time detaching entity will break all relations because there is no "DetachGraph". You can detach entities one-by-one and EF will break navigation properties. I think this is a bug in Entity framework and dynamic proxies.

Community
  • 1
  • 1
Ladislav Mrnka
  • 349,807
  • 56
  • 643
  • 654
  • I traced `LOH` with `ANTS memory profiler` from `RedGate`. It says there are some root objects (like static objects). I'm not sure if `LOH` is caused by `EF` or other parts of my project. Unfortunately traced object is of `System.Object` type which is very general and hard to guess (it has a few properties and I'm trying to find where that object is come from). – Xaqron May 17 '11 at 15:32