Update table with Entity Framework Core migration to add Auto_Increment

asp.net c# entity-framework-core sql-server

Question

I have an ASP.Net Core project with some tables, already link with EF Core. I've made a mistake when creating the database and forgot add auto increment on PK, so when I try to add some data, I can't because EF is trying to insert a null value. I've tried with one table to manually modify the auto increment to 1, and it's ok.

But I am working on multiple computers so my question is: can I create a migration file to update my other table and add auto_increment on their PK ?

Thanks

1
0
8/24/2018 2:27:21 PM

Popular Answer

For the autoincrement as @Collin said, you can add the option with Fluent API and update a migration, I would suggest as well to create a .sql file and update all your records at once before executing the migration, or as part of the same process with a seed method you can update all records from the previous tables and later apply the pending migrations.

This seed method can look like this

 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();
     }
}

Then on your Startup class on the Configure method

 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);
        }
    }
0
8/24/2018 3:12:36 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow