EF (entity framework) usage of “using” statement

我与影子孤独终老i 提交于 2019-12-02 17:08:28

I think you will find many suggesting this style of pattern. Not just me or Henk DBContext handling

  • Yes, Ideally Using statements for DBContext subtypes
  • Even better Unit Of Work patterns that are managed with Using, that have a context and dispose the context Just 1 of many UoW examples, this one from Tom Dykstra
  • The Unit Of Work Manager should be New each Http request
  • The context is NOT thread safe so make sure each thread has its own context.
  • Let EF cache things behind the scenes.
  • Test Context creation times. after several Http request. Do you still have a concern?
  • Expect problems if you store the context in static. any sort of concurrent access will hurt and if you are using parallel AJAX calls, assume 90+% chance of problems if using a static single context.

For some performance tips, well worth a read

The proper or best practice way of using DBContext variable is with the Using.

    using (var db = new MyEntities())
    {
        return db.Items.Where(it => it.ItemId == itemId && !it.IsDeleted).FirstOrDefault();
    }

The benefit is many things are done automatically for us. For example once the block of code is completed the dispose is called.

Per MSDN EF Working with DbContext

The lifetime of the context begins when the instance is created and ends when the instance is either disposed or garbage-collected. Use using if you want all the resources that the context controls to be disposed at the end of the block. When you use using, the compiler automatically creates a try/finally block and calls dispose in the finally block.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!