实体框架:一个数据库,多个 DbContext.这是一个坏主意吗? [英] Entity Framework: One Database, Multiple DbContexts. Is this a bad idea?

查看:31
本文介绍了实体框架:一个数据库,多个 DbContext.这是一个坏主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

迄今为止,我的印象是 DbContext 用于表示您的数据库,因此,如果您的应用程序使用一个数据库,您只需要一个 DbContext.

My impression to date has been that a DbContext is meant to represent your database, and thus, if your application uses one database, you'd want only one DbContext.

然而,一些同事想要将功能区分解为单独的 DbContext 类.

However, some colleagues want to break functional areas out into separate DbContext classes.

我相信这来自一个好地方——希望保持代码更干净——但它似乎不稳定.我的直觉告诉我这是一个坏主意,但不幸的是,我的直觉并不是设计决策的充分条件.

I believe this comes from a good place -- a desire to keep the code cleaner -- but it seems volatile. My gut's telling me it's a bad idea, but unfortunately, my gut feeling is not a sufficient condition for a design decision.

所以我在寻找:

A) 为什么这可能是个坏主意的具体例子;

A) concrete examples of why this might be a bad idea;

B) 保证一切顺利.

推荐答案

单个数据库可以有多个上下文.例如,如果您的数据库包含多个数据库模式并且您希望将它们中的每一个作为单独的自包含区域来处理,它就会很有用.

You can have multiple contexts for single database. It can be useful for example if your database contains multiple database schemas and you want to handle each of them as separate self contained area.

问题是当您想首先使用代码来创建数据库时 - 只有应用程序中的单个上下文可以做到这一点.这个技巧通常是一个包含所有实体的附加上下文,仅用于创建数据库.仅包含实体子集的实际应用程序上下文必须将数据库初始值设定项设置为 null.

The problem is when you want to use code first to create your database - only single context in your application can do that. The trick for this is usually one additional context containing all your entities which is used only for database creation. Your real application contexts containing only subsets of your entities must have database initializer set to null.

在使用多种上下文类型时,您还会遇到其他问题 - 例如共享实体类型及其从一个上下文到另一个上下文的传递等.通常,它可以使您的设计更加清晰并分离不同的功能区域,但是它的代价是额外的复杂性.

There are other issues you will see when using multiple context types - for example shared entity types and their passing from one context to another, etc. Generally it is possible, it can make your design much cleaner and separate different functional areas but it has its costs in additional complexity.

这篇关于实体框架:一个数据库,多个 DbContext.这是一个坏主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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