在存储库模式中使用 ApplicationDbContext

Using ApplicationDbContext in Repository Pattern

我想在我的 ASP.NET MVC 项目中实施存储库模式。我在搜索 google 时看到了很多实现,我有点困惑。他们中的大多数人创建了自己的 Context class,它继承自 DBContext class,然后将其注入到存储库(或多个存储库)构造函数中。 我找到的 None 篇文章解释了为什么创建自定义 DBContext class 以及为什么他们不使用默认的 ApplicationDbContext 以及如何更改您的应用程序代码以适应新的 Context class .他们甚至没有提到 class.

我宁愿使用默认的 ApplicationDbContext,我会在存储库 classes 中注入它,因为目前我看不到创建新 DBContext class 的意义。我错过了什么吗?这是一种不好的做法吗?

如果出于某种原因,我必须添加新的 DbContext class,如何编辑我的代码(web.config 和其他代码)以适应它?如果我已经迁移到数据库,DBContext class 的更改会影响数据库吗?有必要再做一次迁移吗?

举个例子看看MSDN文档: https://docs.microsoft.com/en-us/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application 我只是不知道为什么作者使用 SchoolContext 而不是 ApplicationDbContext。

这是一个广泛的问题,猜测这就是反对票的原因。

你看起来确实很困惑。首先,我不是专家(见要点)。我确实对 default ApplicationDbContext 有所了解。也许你在它弹出的地方使用了一个模板?无论如何,我启动了 MVC-template 并且没有提供默认上下文 class。

简而言之,您可以创建自己的 Context-class。你可以给它任何你想要的名字,只要它以 Context 结尾并且它从 DbContext 继承。如果不是,Entity framework 将无法识别它,并且在构建数据库等时不知道如何处理它。查看您的文章:

The main class that coordinates Entity Framework functionality for a given data model is the database context class. You create this class by deriving from the System.Data.Entity.DbContext class. In your code you specify which entities are included in the data model. You can also customize certain Entity Framework behavior. In this project, the class is named SchoolContext. Blockquote

默认情况下你只有一个 Context-class。

不言而喻,您需要创建自己的 context-class,因为您无法访问 DbContext-class。 (即使可以,你也不应该那样做,你需要将抽象和实现分开。)

我不明白第 2 节。 ApplicationDbContext只是写MySelfNamedContextClass的一种方式。

§3:我不知道使用两个 contect-classes 是否是 possible/feasible,但简单的含义是您将使用两个单独的数据库。这已经很复杂了,你写的不是那个方向。

If I already made migrations to database, would change of DBContext class affect the database? Would it be necessary to do migrations once again?

是的,绝对会。您向其添加 table 或字段或约束或关系...。 根据您带来的变化,您可以做两件事: (i) 添加补充迁移 (ii) 您将不得不倒带迁移 (remove-migration)。可能是您需要将数据库重置为第一次迁移 (update-database 'here name of first migration without the quotation marks'。如果您坚持这样做,并且您仍在本地数据库上,只需通过彻底删除它来删除数据库 (也许在关闭解决方案之后)并倒带并重建迁移并重建数据库。 特别是对于场景(ii),如果你已经在数据库中有数据(没有种子到它),你需要采取措施将它存储在某个地方!!!

我希望这能以某种方式回答您的问题。

亲切的问候。