在三层应用程序中的EF Core中自动迁移 [英] Auto migration in EF Core in three tier application

查看:368
本文介绍了在三层应用程序中的EF Core中自动迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i have three tier application in Asp.net Mvc Core and use EF core, now i want create auto migration ,

我有DAL层,我的上下文在这里提供

i have DAL layer that my context available here

 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不存在,并且不生成迁移,

when i run application database was created and table generate but __migrationhistory doesn't exist and migration not generate,

在启动时,我会删除此行代码

when in start up i remove this line code

 if (!context.Database.EnsureCreated())

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

database was created and __migrationhistory table generated,but my model table not generate,

我该如何解决这个问题? 并在三层应用程序的EF Core中运行自动迁移?

how i can solve this problem ? and run auto migration in EF Core in three tier application?

推荐答案

在EF核心中不存在像EF6中那样的自动迁移.您要么必须先生成迁移,然后再使用

Automatic migration like in EF6 do not exist in EF core. You either have to generate your migrations before starting and then use

context.Database.Migrate();

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

or you drop your whole database on each launch and use

context.Database.EnsureCreated();

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

to recreate the updated database. The second one wont allow you to add any migrations later on, so you have to recreate entire database each time. To delete database you can use

context.Database.EnsureDeleted();

这篇关于在三层应用程序中的EF Core中自动迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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