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

查看:21
本文介绍了为什么在使用实体框架时重新启动 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.

了解了使用实体框架的所有优点,一些变得毫无用处,因为我们每次都在重新创建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.

你有什么看法?

推荐答案

Managing Lifetime

您是正确的,DbContext 的单个静态实例通常是不推荐的:

Managing Lifetime

You're correct that a single static instance of DbContext is usually not recommended:

您使用 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 ...

处理短期上下文的常用方法是将其包装在 using 块中:

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 : 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.)

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

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