Proper use of “Using” statement for datacontext

后端 未结 5 518
醉酒成梦
醉酒成梦 2021-02-06 05:08

I’m using Linq to Entities and lately, I found that a lot of folks recommending wrapping the datacontext in a using statement like this:

Using(DataContext db = n         


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-02-06 06:01

    Considering the code provided I see, you esplicitly use readonly DataContext db = new DataContext(); like a global variable, so you consider to have that object lifetime along with your rCustomer class instance lifetime.

    If this is true, what you can do, instead of rewriting everything, you can implement IDisposable and inside Dispose() code something like

    private void Dispose()
    {
        if(db  != null) 
            db.Dispose();
    }
    

    Hope this helps.

提交回复
热议问题