【问题标题】:Update table with Entity Framework Core migration to add Auto_Increment使用 Entity Framework Core 迁移更新表以添加 Auto_Increment
【发布时间】:2019-01-28 22:14:32
【问题描述】:

我有一个带有一些表的 ASP.Net Core 项目,已经与 EF Core 链接。 我在创建数据库时犯了一个错误,忘记在 PK 上添加自动增量,所以当我尝试添加一些数据时,我不能,因为 EF 试图插入一个空值。我试过用一张表手动修改自增为1,没问题。

但是我在多台计算机上工作,所以我的问题是:我可以创建一个迁移文件来更新我的其他表并在他们的 PK 上添加 auto_increment 吗?

谢谢

【问题讨论】:

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


    【解决方案1】:

    您可以通过 Fluent API 使用.UseSqlServerIdentityColumn(),然后添加迁移。

    虽然如果不提供当前配置代码就很难进行演示,但下面是一个示例:

    public class BaseEntityTypeConfiguration<TEntity> : IEntityTypeConfiguration<TEntity> where TEntity : BaseEntity
    {
        public virtual void Configure(EntityTypeBuilder<TEntity> entityTypeBuilder)
        {
            entityTypeBuilder.Property(x => x.Id)
                             .UseSqlServerIdentityColumn();
        }
    }
    

    source

    【讨论】:

      【解决方案2】:

      对于@Collin 所说的自动增量,您可以使用 Fluent API 添加选项并更新迁移,我建议在执行迁移之前创建一个 .sql 文件并立即更新所有记录,或者作为一部分使用种子方法的相同过程,您可以更新以前表中的所有记录,然后应用挂起的迁移。

      这个种子方法可以是这样的

       public static class DbContextExtensions
          {
              public static void EnsureIdUpdates(this DbContext context)
              {
                   //CHOOSE HERE if you want to execute a sql script using Context.Set<YourEntity>().FromSql   
                   //OR
      
                  //Do here a check to ensure that this method will be called just once as part of your migrations, for example if you ran this code before, you would be able to check that some records has an Id != 0 and you don't need to update the Ids again
                  var dataToUpdate = context.Set<YourEntity>();
                  int count = 0;
                  dataToUpdate.ForEachAsync(x => { x.Id = count++; }).Wait();
                  context.SaveChanges();
           }
      }
      

      然后在你的 Startup 类上的 Configure 方法

       public void Configure(IApplicationBuilder app, IHostingEnvironment en, DbContext context)
       {
         ....
          context.EnsureIdUpdates();
          context.ApplyMigrations();
      }
      
      
      
      public static void ApplyMigrations(this DbContext dbContext, string[] excludeMigrations = null)
          {
              var pendingMigrations = dbContext.Database.GetPendingMigrations();
      
              foreach (var migration in pendingMigrations)
              {
                  if (excludeMigrations != null && excludeMigrations.Contains(migration))
                      continue;
      
                  dbContext.Database.Migrate(migration);
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2017-02-06
        • 1970-01-01
        • 2019-01-11
        • 2018-06-08
        • 2017-06-17
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多