1

基于示例MVC5项目,我试图学习处理迁移的正确方法。获取多个DbContexts以使用迁移相同的数据库

在根目录中我有一个名为“DbContexts”与两个Contextes的文件夹。

第一招: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东西?

回答

2

建议:如果你只是做一个示例项目来学习如你所说的迁移,坚持一个DbContext。保持简单 - 将您的实体合并到一个DbContext中,该DbContext继承自IdentityDbContext<ApplicationUser>

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

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

+0

好的,你在说可以将我的模型添加到默认的DbContext中吗?我见过的每个示例都将ASP.NET Identity保留为默认值,然后创建自己的调用相同数据库的DbContext,并且遇到问题,告诉Migrations同时接受这两个DbContext。 – Kaleet

+0

是的,它应该没问题。他们只是给你一个默认的DbContext开箱 - 你可以根据需要修改它,但你不需要创建第二个。我已经看过一些关于使用独立IdentityContext和其他上下文的文章,但对我来说,它只是过于复杂,除非你正在处理某些场景。 – Jack

相关问题