【问题标题】:Getting multiple DbContexts to use Migrations with the same database让多个 DbContexts 使用同一个数据库的迁移
【发布时间】:2014-01-29 23:38:06
【问题描述】:

基于示例 MVC5 项目,我正在尝试学习处理迁移的正确方法。

在根目录中,我有一个名为“DbContexts”的文件夹,其中包含两个上下文。

第一个:IdentityContext.cs

    public class IdentityContext : IdentityDbContext<ApplicationUser>
{
    public IdentityContext()
        : base("DefaultConnection")
    { }
}

然后我有一个名为 IdentityMigrations 的文件夹,其中包含 Configuration.cs

    internal sealed class Configuration : DbMigrationsConfiguration<TryFive.Web.DbContexts.IdentityContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = true;
        MigrationsDirectory = @"DbContexts\IdentityMigrations";
    }

    protected override void Seed(TryFive.Web.DbContexts.IdentityContext context)
    {
        //  This method will be called after migrating to the latest version.

        //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
        //  to avoid creating duplicate seed data. E.g.
        //
        //    context.People.AddOrUpdate(
        //      p => p.FullName,
        //      new Person { FullName = "Andrew Peters" },
        //      new Person { FullName = "Brice Lambson" },
        //      new Person { FullName = "Rowan Miller" }
        //    );
        //
    }
}

然后我有具有相似属性的 MyContexts。

当我尝试运行“更新数据库”命令时,我收到以下错误消息:The type 'TryFive.Web.DbContexts.IdentityContext' does not inherit from 'System.Data.Entity.Migrations.DbMigrationsConfiguration'. Migrations configuration types must extend from 'System.Data.Entity.Migrations.DbMigrationsConfiguration'.

关于如何解决这个问题或更好的方法来做这个 DbContext 的任何想法?

【问题讨论】:

    标签: c# entity-framework ef-code-first asp.net-mvc-5 entity-framework-migrations


    【解决方案1】:

    建议:如果您只是按照您所说的那样做一个示例项目来学习迁移,请坚持使用一个 DbContext。保持简单 - 将您的实体合并到一个继承自 IdentityDbContext&lt;ApplicationUser&gt; 的 DbContext 中

    删除您已创建的现有迁移文件夹 - 并在删除第二个 DbContext 后重新“启用迁移”。这将帮助您继续学习迁移,而不是学习如何在一个项目中使用两个 DbContext。

    另外,@Lajos,我不确定您说的是哪个 MVC,但我的 DbContext 从未继承自 DbMigrationsConfiguration - 它们继承自 DbContext 或 IdentityDbContext。您指的是在项目上发布“启用迁移”时生成的 MigrationsConfiguration 类。它用于生成迁移和播种数据。

    【讨论】:

    • 好吧,你是说可以将我的模型添加到默认的 DbContext 中?我见过的每个示例都将 ASP.NET 标识保留为默认值,然后创建自己的 DbContext 来调用同一个数据库,我在告诉 Migrations 接受两个 DbContexts 时遇到问题。
    • 是的,应该没问题。他们只是为您提供了一个开箱即用的默认 DbContext - 您可以根据需要对其进行修改,但您不需要创建第二个。我已经看过一些关于使用单独的 IdentityContext 和其他上下文的帖子,但对我来说,除非你正在处理某些场景,否则它只是过于复杂了。
    • 对于问题标题,我不确定您是否正在帮助搜索引擎提供此答案。哈哈。
    猜你喜欢
    • 1970-01-01
    • 2017-07-07
    • 2019-10-02
    • 2012-10-01
    • 2020-01-23
    • 1970-01-01
    • 2018-01-07
    • 2016-12-09
    • 2020-02-28
    相关资源
    最近更新 更多