C# EF(实体框架)使用“using”语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17944837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 10:53:34  来源:igfitidea点击:

EF (entity framework) usage of "using" statement

c#entity-frameworkgarbage-collectiondbcontextusing-statement

提问by Pal

I have a project on MVC. We chose EF for our DB transactions. We created some managers for the BLL layer. I found a lot of examples, where "using" statement is used, i.e.

我有一个关于 MVC 的项目。我们为我们的数据库事务选择了 EF。我们为 BLL 层创建了一些管理器。我找到了很多例子,其中使用了“ using”语句,即

public Item GetItem(long itemId)
    {
        using (var db = new MyEntities())
        {
            return db.Items.Where(it => it.ItemId == itemId && !it.IsDeleted).FirstOrDefault();
        }
    }

Here we create a new instance of DBcontext MyEntities(). We using "using" in order to "ensure the correct use of IDisposable objects."

在这里,我们创建了一个 DBcontext 的新实例MyEntities()。我们使用“ using”是为了“确保正确使用 IDisposable 对象”。

It's only one method in my manager. But I have more than ten of them. Every time I call any method from the manager I'll be using "using" statement and create another DBcontext in the memory. When will the garbage collector (GC) dispose them? Does anyone know?

这只是我经理的一种方法。但我有十多个。每次我从管理器调用任何方法时,我都会使用“ using”语句并在内存中创建另一个 DBcontext。垃圾收集器 (GC) 何时处理它们?有人知道吗?

But there is alternative usage of the manager methods. We create a global variable:

但是管理器方法还有其他用途。我们创建一个全局变量:

private readonly MyEntities db = new MyEntities();

and use DBcontext in every method without "using" statement. And method looks like this:

并在没有“ using”语句的每个方法中使用 DBcontext 。方法如下所示:

public Item GetItem(long itemId)
{
    return db.Items.Where(it => it.ItemId == itemId && !it.IsDeleted).FirstOrDefault();
}

Questions:

问题:

  1. What is the proper way of using DBcontext variable?
  2. What if we wouldn't use "usage" statement (because it affects the performance) - GC will do all for that?
  1. 使用 DBcontext 变量的正确方法是什么?
  2. 如果我们不使用 " usage" 语句(因为它会影响性能)怎么办 - GC 会为此做所有事情?

I'm a "rookie" in EF usage and still haven't found the unequivocal answer for this question.

我是 EF 使用中的“菜鸟”,仍然没有找到这个问题的明确答案。

采纳答案by phil soady

I think you will find many suggesting this style of pattern. Not just me or Henk DBContext handling

我想你会发现很多人建议采用这种模式。不仅仅是我或 Henk DBContext 处理

  • Yes, Ideally Using statements for DBContext subtypes
  • Even better Unit Of Work patterns that are managed with Using, that have a context and dispose the context Just 1 of many UoW examples, this one from Tom Dykstra
  • The Unit Of Work Manager should be New each Http request
  • The context is NOT thread safe so make sure each thread has its own context.
  • Let EF cache things behind the scenes.
  • Test Context creation times. after several Http request. Do you still have a concern?
  • Expect problems if you store the context in static. any sort of concurrent access will hurt and if you are using parallel AJAX calls, assume 90+% chance of problems if using a static single context.
  • 是的,理想情况下使用 DBContext 子类型的语句
  • 使用 Using 管理的更好的工作单元模式,具有上下文并处理上下文许多 UoW 示例中的一个,来自 Tom Dykstra
  • 工作单元管理器应该是新的每个 Http 请求
  • 上下文不是线程安全的,因此请确保每个线程都有自己的上下文。
  • 让 EF 在幕后缓存东西。
  • 测试上下文创建时间。经过几次Http请求。你还有顾虑吗?
  • 如果您将上下文存储在静态中,则会出现问题。任何类型的并发访问都会受到伤害,如果您使用并行 AJAX 调用,则假设使用静态单个上下文时出现问题的可能性为 90% 以上。

For some performance tips, well worth a read

对于一些性能提示,非常值得一读

回答by Catto

The proper or best practice way of using DBContext variable is with the Using.

使用 DBContext 变量的正确或最佳实践方法是使用。

    using (var db = new MyEntities())
    {
        return db.Items.Where(it => it.ItemId == itemId && !it.IsDeleted).FirstOrDefault();
    }

The benefit is many things are done automatically for us. For example once the block of code is completed the dispose is called.

好处是很多事情都是自动为我们完成的。例如,一旦代码块完成,就会调用 dispose。

Per MSDN EF Working with DbContext

每个MSDN EF 使用 DbContext

The lifetime of the context begins when the instance is created and ends when the instance is either disposed or garbage-collected. Use using if you want all the resources that the context controls to be disposed at the end of the block. When you use using, the compiler automatically creates a try/finally block and calls dispose in the finally block.

上下文的生命周期在创建实例时开始,并在实例被释放或垃圾收集时结束。如果您希望将上下文控制的所有资源都放在块的末尾,请使用 using。使用 using 时,编译器会自动创建一个 try/finally 块并在 finally 块中调用 dispose 。