ObjectContextScope – Entity Framework v1

#entityframework

Posted by admin on September 01, 2019

A while ago I had written some code to cope with the ever annoying issue on entities existing in different scopes… The problem is that one scope would not know if it was wrapped up in another scope, this would stop any type of abstraction know to mankind.

Anyway's to cut a long story short I decided to do something similar to the TransactionScope and create a ObjectContextScope. This would now allow me to use Ambient scopes so that only one object context was being used at any one time unless otherwise stated.

An example as shown below is that

scope1 will create the initial object context of dbEntities.

scope2 will use scope1 object context as the objectcontext is of the same type of dbEntities.

scope3 will create its own object context, which can only be used in scope3

scope4 is of a different objectcontext type, so a new objectcontext is created of type db2Entities.

scope 5 will use scope1 object context as scope 3 is only for scope3 and cannot be used inside any other scope.

using(ObjectContextScope scope1 = new ObjectContextScope()) {
 using(ObjectContextScope scope2 = new ObjectContextScope()) {
  using(ObjectContextScope scope3 = new ObjectContextScope(ObjectContextScopeOption.RequiresNew)) {
   using(ObjectContextScope scope4 = new ObjectContextScope(ObjectContextScopeOption.Required)) {}
   using(ObjectContextScope scope5 = new ObjectContextScope(ObjectContextScopeOption.RequiresNew)) {

   }
  }
 }
}

Here is the project on codeplex, http://objectcontextscope.codeplex.com