I am new to EF5 Code First and I'm tinkering with a proof-of-concept before embarking on a project at work.
I have initially created a model that looked something like
public class Person { public int Id { get; set; } public string FirstName { get; set;} public string Surname {get;set;} public string Location {get;set;} }
And I added a few records using a little MVC application I stuck on the top.
Now I want to change the Location column to an enum, something like:
public class Person { public int Id { get; set; } public string FirstName { get; set;} public string Surname {get;set;} public Locations Location {get;set;} } public enum Locations { London = 1, Edinburgh = 2, Cardiff = 3 }
When I add the new migration I get:
AlterColumn("dbo.People", "Location", c => c.Int(nullable: false));
but when I run update-database I get an error
Conversion failed when converting the nvarchar value 'London' to data type int.
Is there a way in the migration to truncate the table before it runs the alter statement?
I know I can open the database and manually do it, but is there a smarter way?
Now it's time to use the Code First Migration approach. Open Package Manager Console. Run Enable-Migrations command in a Package Manager console. This command added two more classes to your project in the Migrations folder.
Go to the Package Manager Console and install the needed tools with Install-Package Microsoft. EntityFrameworkCore. Tools . When it has completed try to use the command EntityFrameworkCore\Add-Migration firstMigration .
The smartest way is probably to not alter types. If you need to do this, I'd suggest you to do the following steps:
Sql()
to take over the data from the original column using an update statementThis can all be done in the same migration, the correct SQL script will be created. You can skip step 2 if you want your data to be discarded. If you want to take it over, add the appropriate statement (can also contain a switch statement).
Unfortunately Code First Migrations do not provide easier ways to accomplish this.
Here is the example code:
AddColumn("dbo.People", "LocationTmp", c => c.Int(nullable: false)); Sql(@" UPDATE dbp.People SET LocationTmp = CASE Location WHEN 'London' THEN 1 WHEN 'Edinburgh' THEN 2 WHEN 'Cardiff' THEN 3 ELSE 0 END "); DropColumn("dbo.People", "Location"); RenameColumn("dbo.People", "LocationTmp", "Location");
Based on @JustAnotherUserYouMayKnow's answer, but easier.
Try firstly execute Sql()
command and then AlterColumn()
:
Sql(@" UPDATE dbo.People SET Location = CASE Location WHEN 'London' THEN 1 WHEN 'Edinburgh' THEN 2 WHEN 'Cardiff' THEN 3 ELSE 0 END "); AlterColumn("dbo.People", "Location", c => c.Int(nullable: false));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With