One DbContext per web request… why?

后端 未结 9 1254
死守一世寂寞
死守一世寂寞 2020-11-21 22:09

I have been reading a lot of articles explaining how to set up Entity Framework\'s DbContext so that only one is created and used per HTTP web request using var

9条回答
  •  时光取名叫无心
    2020-11-21 22:46

    Another issue to watch out for with Entity Framework specifically is when using a combination of creating new entities, lazy loading, and then using those new entities (from the same context). If you don't use IDbSet.Create (vs just new), Lazy loading on that entity doesn't work when its retrieved out of the context it was created in. Example:

     public class Foo {
         public string Id {get; set; }
         public string BarId {get; set; }
         // lazy loaded relationship to bar
         public virtual Bar Bar { get; set;}
     }
     var foo = new Foo {
         Id = "foo id"
         BarId = "some existing bar id"
     };
     dbContext.Set().Add(foo);
     dbContext.SaveChanges();
    
     // some other code, using the same context
     var foo = dbContext.Set().Find("foo id");
     var barProp = foo.Bar.SomeBarProp; // fails with null reference even though we have BarId set.
    

提交回复
热议问题