EF Core中的三层应用程序中的自动迁移

时间:2017-03-06 08:04:08

标签: c# asp.net-mvc asp.net-core entity-framework-core

我在Asp.net Mvc Core中有三层应用程序并使用EF核心, 现在我想创建自动迁移,

我有DAL图层,我的上下文可以在这里找到

 public class AdminContext : DbContext
    {

    public AdminContext(DbContextOptions<AdminContext> options) : base(options)
    {

    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<AdsAdsCategory>()
             .HasKey(bc => new { bc.AdsId, bc.AdsCategoryId });

        modelBuilder.Entity<AdsAdsCategory>()
            .HasOne(bc => bc.Ads)
            .WithMany(b => b.AdsAdsCategories)
            .HasForeignKey(bc => bc.AdsId);

        modelBuilder.Entity<AdsAdsCategory>()
            .HasOne(bc => bc.Category)
            .WithMany(c => c.AdsAdsCategories)
            .HasForeignKey(bc => bc.AdsCategoryId);
    }

    public DbSet<Ads> Adses { get; set; }
    public DbSet<AdsCategory> AdsCategories { get; set; }
    public DbSet<AdsPosition> AdsPositions { get; set; }
    public DbSet<AdsCustomer> AdsCustomers { get; set; }
}

并在我的应用程序启动

我写这段代码

var context = app.ApplicationServices.GetService<AdminContext>();

       if (!context.Database.EnsureCreated())
            context.Database.Migrate();

当我运行应用程序数据库时创建并生成表但__migrationhistory不存在且迁移不生成,

启动时删除此行代码

 if (!context.Database.EnsureCreated())

创建了数据库并生成了__migrationhistory表,但我的模型表没有生成,

我怎么能解决这个问题? 并在三层应用程序中在EF Core中运行自动迁移?

2 个答案:

答案 0 :(得分:2)

EF核心中不存在EF6中的自动迁移。您必须在开始之前生成迁移,然后使用

context.Database.Migrate();

或者在每次启动时删除整个数据库并使用

context.Database.EnsureCreated();

重新创建更新的数据库。 第二个不允许您稍后添加任何迁移,因此您每次都必须重新创建整个数据库。要删除数据库,您可以使用

context.Database.EnsureDeleted();

答案 1 :(得分:2)

您需要执行以下操作才能在MVC .NET Core中启用迁移。

1-在Visual Studio中打开程序包管理器控制台。输入并执行此代码。

add-migration ClassName

pm> add-migration FirstInitialize

2-执行代码后,将为您的模型创建迁移类

 public partial class FirstInitialize : Migration
 {
    protected override void Up(MigrationBuilder migrationBuilder)
   {
  //After executing the code, this section will be automatically   generated for your models 
   }

}

3-然后,在program.cs main方法的class部分中输入以下代码,您的模型将被构建到数据库中。

using (var scope = host.Services.CreateScope())
    {
        var services = scope.ServiceProvider;
        try
        {
            var context = services.GetRequiredService<YouDbContext>();
            context.Database.Migrate();
        }
        catch (Exception ex)
        {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred while seeding the atabase.");
        }
    }

4-每次更改模型或添加新模型时,都必须重复执行步骤。每次为迁移选择一个新名称。  样本:

pm> add-migration SecondInitialize

*我的英语不是很好