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

2024-04-27

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

我有 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 中运行自动迁移?


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

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

添加迁移类名

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 方法的类部分中输入以下代码,您的模型将被构建到数据库中。

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

*我英语说得不好

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

三层应用程序中 EF Core 的自动迁移 的相关文章

随机推荐