How to update tables (not recreate them) using .net core entity framework migration

.net-core asp.net-core-2.0 c# entity-framework-core

Question

I have connected to an existing SQL database that didn't have any identity, eg no aspNetUser table etc. I have since added these using a custom login class like this

public class UserLogin : IdentityUser
{       
    public int LanguageId { get; set; }
    public string HQ_PRM_Id { get; set; }       
}

I then generated a migration to create the tables like this (I just called it identity)

"dotnet ef migrations add Identity"

I then ran the migration using

"dotnet ef database update Identity"

That created the tables so all good. However, I forgot to add a firstname and lastname to the user class which I have since added. The problem is when I run my new migration it says

There is already an object named 'AspNetRoles' in the database.

How do I tell the migration to update the schema and not try to recreate the tables? Otherwise I have to manually delete the objects first.. which means losing data.

Thanks

1
0
11/13/2019 9:45:47 AM

Accepted Answer

During development models frequently change and these models (which represent database tables) get out of sync with the tables themselves. The role of migrations is to keep the database and the models in sync and therefore whenever you make a change to the model you must create a new migration to incrementally update the database schema.

Initial migration

public class UserLogin : IdentityUser
{       
    public int LanguageId { get; set; }
    public string HQ_PRM_Id { get; set; }       
}

dotnet ef migrations add Identity - This command creates a new migration called Identity

dotnet ef database update Identity - This command runs migrations upto and including one with the name "Identity"

Second migration

public class UserLogin : IdentityUser
{       
    public int LanguageId { get; set; }
    public string HQ_PRM_Id { get; set; }
    public string FirstName { get; set; }       
    public string LastName { get; set; }            
}

dotnet ef migrations add AddNames - This command creates a new migration called AddNames which EF should recognise is an update to the exsiting tables (and therefore the migration should only be and update)

dotnet ef database update AddNames - This will then run the AddNames migration

I'd definitely recommend checking the MS docs on the subject

0
11/13/2019 10:16:20 AM


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