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

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

问题描述

到目前为止,我的印象是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. 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)具体的例子为什么这可能是一个坏主意,或者B)保证这一切都会很好的。

So I'm looking for A) concrete examples of why this might be a bad idea, or B) assurances that this'll all work out just fine.

推荐答案

你可以单个数据库的多个上下文。例如,如果您的数据库包含多个数据库模式,并且希望将它们分别处理为独立的自包含区域,那么这可能很有用。

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.

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

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