简体   繁体   English

什么时候需要配置数据库连接

[英]When is it necessary to dispose db connection

I have a class that contains several common methods customized for use in my MVC app, that I use in several places. 我有一个类,其中包含为我的MVC应用程序定制的几种常用方法,我在几个地方使用。 Here is an example of some: 这是一些例子:

    private MyEntities db = new MyEntities();


    public List<SelectListItem> GetLocationList()
    {
        var query =
                db.v_LocationsAlphabetical.OrderByDescending(x => x.Category).ThenBy(x => x.LocationName).ToList()
                .Select(x => new SelectListItem
                {
                    Value = x.LocationID.ToString(),
                    Text = x.LocationName
                });

        return (query).ToList();
    }

    public IEnumerable<SelectListItem> GetStates()
    {
        var query = db.States.Select(x => new SelectListItem
        {
            Value = x.Abbr,
            Text = x.Name
        });

        return(query);
    }

    public List<Person> GetPeople()
    {
        var query = db.Person.OrderBy(m => m.LastName).ThenBy(m => m.FirstName).ToList();

        return (query);

    }

Each one of these methods makes a call to the database to get data and I was wondering if I need to add a dispose to each method. 这些方法中的每一个都调用数据库来获取数据,我想知道是否需要为每个方法添加一个dispose。 If not, why? 如果没有,为什么? Thanks. 谢谢。

You shouldn't call dispose in each method, because the lifetime of db is the same as that of the enclosing class since it's not a local variable in a method. 您不应该在每个方法中调用dispose,因为db的生命周期与封闭类的生命周期相同,因为它不是方法中的局部变量。

The typical way to handle this is to make the current class IDisposable and call db.Dispose() in the Dispose() method. 处理此问题的典型方法是使当前类IDisposable并在Dispose()方法中调用db.Dispose()

No. DbContexts don't have to be manually disposed, unless you manually manage the connection yourself. 不需要手动处理DbContexts,除非您自己手动管理连接。 Therefore, disposing them is usually optional. 因此,处理它们通常是可选的。

There are multiple ways of handling db connection in .NET 在.NET中有多种处理数据库连接的方法
One of my favorites is the one called one dbcontext per request , which basically means you initialize your dbcontext when needed, do the work without thinking about instantiating or disposing, and dispose automatically when the request is done. 我最喜欢的一个one dbcontext per request ,它基本上意味着你在需要时初始化dbcontext,不考虑实例化或处理就完成工作,并在请求完成时自动处理。 (kinda UnitOfWork-ish) (有点UnitOfWork-ish)

I've already shown this approach here . 我已经在这里展示了这种方法。 It's not only applicable to EF, but to Linq2SQL, ADO.NET, etc. as well. 它不仅适用于EF,也适用于Linq2SQL,ADO.NET等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM