Is Disposing of Entity Framework context object required

后端 未结 5 1519
臣服心动
臣服心动 2021-02-07 09:39

We are using entity framework for communication with database in our WCF service methods, recently we run the code review tool on our service code. As usual we got many review p

5条回答
  •  情歌与酒
    2021-02-07 10:09

    The recommended thing to do with a DBContext is to not dispose of it at all (it is the exception to the rule in most cases), even though is a disposable object.

    An example of the issue, ths first example is taking a call and evaluation it in the using statement, while the second evaluates it after. (first ons runs, second one throws error The operation cannot be completed because the DbContext has been disposed.)

    List listT;
    using (Model1 db = new Model1())
    {
        listT = db.Tests.ToList(); //ToList Evaluates
    }
    foreach (var a in listT)
    {
        Console.WriteLine(a.value);
    }
    
    IEnumerable listT1;
    using (Model1 db = new Model1())
    {
        listT1 = db.Tests;
    }
    foreach (var a in listT1) //foreach evaluates (but at wrong time)
    {
        Console.WriteLine(a.value);
    }
    

    The same issue happens in

    IEnumerable listT1;
    Model1 db = new Model1();
    listT1 = db.Tests;
    db.Dispose();
    foreach (var a in listT1) //foreach evaluates (but at wrong time)
    {
        Console.WriteLine(a.value);
    }
    

    Aslong as you dont open the connection manually you are safe by just using

    IEnumerable listT1;
    Model1 db = new Model1();
    listT1 = db.Tests;
    foreach (var a in listT1) //foreach evaluates (but at wrong time)
    {
        Console.WriteLine(a.value);
    }
    

    and never disposing. as it will take care of itself under most circumstances, as thats what it's designed to do.

    Now should you open up a connection by force then the context wont close it automatically when the transfer is done, as it don't know when and then you must/should dispose the object or close the connection and keep the object undisclosed.

    Extra midnight reading:

    1. http://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext.html#.U6WdzrGEeTw
    2. https://msdn.microsoft.com/en-us/data/jj729737.aspx

提交回复
热议问题