实体框架和调用context.dispose()

什么时候应该调用DbContext.dispose()实体框架?


这种假想的方法不好吗?


public static string GetName(string userId)

{

    var context = new DomainDbContext();

    var userName = context.UserNameItems.FirstOrDefault(x => x.UserId == userId);

    context.Dispose();

    return userName;

}

这是否更好?


public static string GetName(string userId)

{

    string userName;

    using(var context = new DomainDbContext()) {

        userName = context.UserNameItems.FirstOrDefault(x => x.UserId == userId);

        context.Dispose();

    }

    return userName;

}

这是否更好,也就是说,在使用using()时不应该调用context.Dispose()吗?


public static string GetName(string userId)

{

    string userName;

    using(var context = new DomainDbContext()) {

        userName = context.UserNameItems.FirstOrDefault(x => x.UserId == userId);

    }

    return userName;

}


慕雪6442864
浏览 810回答 3
3回答

慕田峪4524236

实际上,这是两个问题合二为一:我应该何时Dispose()上下文?我的背景寿命应该是什么?答案:永远不会 1。using是隐Dispose()在一个try-finally块中。Dispose较早发生异常时,可能会丢失单独的语句。此外,在最常见的情况下,不是要求Dispose所有(隐或显式)是不会对人体有害。参见例如Entity Framework 4-Winform应用程序中的上下文寿命/范围。简而言之:寿命应该是“短的”,静态上下文是不好的。1正如某些人所评论的,该规则的一个例外是,上下文是实现IDisposable自身并共享其生命周期的组件的一部分。在这种情况下,您需要调用组件context.Dispose()的Dispose方法。

DIEA

我遵循了一些使用EF的很好的教程,但它们没有处理上下文。我对此感到有点好奇,我注意到即使是受人尊敬的Microsoft VIP也不会处理上下文。我发现您在正常情况下不必将dbContext处置。

蝴蝶刀刀

您可以将数据库上下文定义为类字段,然后实施IDisposable。如下所示:public class MyCoolDBManager : IDisposable{    // Define the context here.    private DomainDbContext _db;    // Constructor.    public MyCoolDBManager()    {        // Create a new instance of the context.        _db = new DomainDbContext();    }    // Your method.    public string GetName(string userId)    {                   string userName = _db.UserNameItems.FirstOrDefault(x => x.UserId == userId);        return userName;    }     // Implement dispose method.    // NOTE: It is better to follow the Dispose pattern.    public void Dispose()    {         _db.dispose();         _db = null;    }}
打开App,查看更多内容
随时随地看视频慕课网APP