Do I need to force a Dispose after a LINQ query?

前端 未结 6 1955
野趣味
野趣味 2021-02-12 22:49

My DBA says that there are way too many connection open and he thinks it is my code in .net that is leaving them open.

I am using LINQ querys and EF code first.

6条回答
  •  心在旅途
    2021-02-12 23:20

    Yes, if your method defines a Unit of Work; no, if something more primitive. (P.S. something somewhere in your code should define a Unit of Work, and that thing should be wrapped in a using (var context = new DbContext()) {} or equivalent.)

    And if you belong to the school of thought that your DbContext is your Unit of Work, then you'll always be wrapping that bad boy with a using block: the local caching of data previously fetched during the context lifetime together with the SaveChanges method act as a sort of lightweight transaction, and your Dispose (without calling SaveChanges) is your Rollback (whereas your SaveChanges is your Commit).

提交回复
热议问题