为什么在使用Entity Framework时重新启动DbContext? [英] Why re-initiate the DbContext when using the Entity Framework?

查看:128
本文介绍了为什么在使用Entity Framework时重新启动DbContext?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道是否有更好的方法使用 DbContext ,因为在使用WCF时不建议将其设置为静态。因此,我们每次要访问数据库时都会创建它。

I don't know if there is a better way to use the DbContext because it is not recommended to set is as static when working with WCF. So we are creating it each time we want to access the database.

了解使用Entity Framework的所有优点,因为我们每次重新创建 DbContext 更多的可能会导致开销,因为要创建大实体模型的过程。

Knowing all the advantages of using Entity Framework, some become useless since we are recreating the DbContext each time; and more may cause overhead since the process of creating big entity models is to be considered.

你的意见是什么?

推荐答案

管理生命周期



您的一个静态实例 DbContext


使用ObjectContext越多,通常越大。
这是因为它持有对所有已经有
的实体的引用,基本上是你已经查询,添加或附加的。
所以你应该重新考虑无限期共享相同的ObjectContext。

The more you use an ObjectContext, generally the bigger it gets. This is because it holds a reference to all the Entities it has ever known about, essentially whatever you have queried, added or attached. So you should reconsider sharing the same ObjectContext indefinitely.

这些注释直接适用于 DbContext ,因为它包裹了 ObjectContext 来公开简化和更直观的API。 [查看文档]

These comments apply directly to the DbContext, because it wraps wraps ObjectContext to expose "simplified and more intuitive APIs." [see documentation]

创建上下文的开销相对较低:

The overhead of creating the context is relatively low:


现实是这个成本实际上相当低,因为大部分的
只是通过引用来复制元数据全局缓存
到新的ObjectContext中。一般来说,我不认为这个成本值得担心...

The reality is this cost is actually pretty low, because mostly it simply involves copying, by reference, metadata from a global cache into the new ObjectContext. Generally I don’t think this cost is worth worrying about ...

使用短命的上下文的常见方法是将它包装在一个使用块中:

The common way to work with a short-lived context is to wrap it in a using block:

using(DbContext context = new SomeDbContext())
{
    // Do work with context
}

为了方便测试,您可能需要让您的 DbContext 实现一些 IDbContext 界面,并创建一个工厂类 ContextFactory< T>其中T:IDbContext 来实例化上下文。

To ease with testing, you may want to have your DbContext implement some IDbContext interface, and create a factory class ContextFactory<T> where T : IDbContext to instantiate contexts.

这允许您轻松地将任何 IDbContext 交换到代码中(即内存上下文为对象嘲笑。)

This allows you to easily swap any IDbContext into your code (ie. an in-memory context for object mocking.)

  • MSDN: How to decide on a lifetime for your ObjectContext
  • StackOverflow: Instantiating a context in LINQ to Entities

这篇关于为什么在使用Entity Framework时重新启动DbContext?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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