实体框架和调用context.dispose() [英] Entity Framework and calling context.dispose()

查看:104
本文介绍了实体框架和调用context.dispose()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时应使用实体框架调用 DbContext.dispose()

When should one call DbContext.dispose() with entity framework?


  1. 这个假想方法不好吗?

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;
    }
    


  • 这是否更好,也就是说,

    public static string GetName(string userId)
    {
        string userName;
        using(var context = new DomainDbContext()) {
            userName = context.UserNameItems.FirstOrDefault(x => x.UserId == userId);
        }
        return userName;
    }
    



  • 推荐答案

    实际上这是两个问题合而为一:

    In fact this is two questions in one:


    1. 我什么时候应该 Dispose()的上下文?

    2. 我的上下文的寿命应该是什么?

    1. When should I Dispose() of a context?
    2. What should be the lifespan of my context?

    答案:


    1. 从不 1 使用是在最终尝试 Dispose() >块。较早发生异常时,可能会丢失单独的 Dispose 语句。另外,在大多数情况下,根本不调用 Dispose (隐式或显式)无害

    1. Never 1. using is an implicit Dispose() in a try-finally block. A separate Dispose statement can be missed when an exception occurs earlier. Also, in most common cases, not calling Dispose at all (either implicitly or explicitly) isn't harmful.

    参见例如实体框架4-寿命/上下文范围Winform应用程序。简而言之:寿命应该是短的,静态上下文是不好的。

    See e.g. Entity Framework 4 - lifespan/scope of context in a winform application. In short: lifespan should be "short", static context is bad.






    1 正如某些人所评论的那样,该规则的一个例外是当上下文是实现 IDisposable 本身并共享其内容的组件的一部分时生命周期。在这种情况下,您可以在组件的 Dispose 方法中调用 context.Dispose()


    1 As some people commented, an exception to this rule is when a context is part of a component that implements IDisposable itself and shares its life cycle. In that case you'd call context.Dispose() in the Dispose method of the component.

    这篇关于实体框架和调用context.dispose()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆