EF (entity framework) usage of “using” statement

前端 未结 2 864
[愿得一人]
[愿得一人] 2021-01-31 03:51

I have a project on MVC. We chose EF for our DB transactions. We created some managers for the BLL layer. I found a lot of examples, where \"using\" statement is us

2条回答
  •  情深已故
    2021-01-31 04:40

    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.

提交回复
热议问题