1

I have redesigned my class scheme many times since started the project I'm working on.

At first I didn't know about data annotations, so I have migration1, where my Ids have no DatabaseGenerated.Identity option and migration4 where they already have it.

Turns out that EF doesn't work this way (https://entityframework.codeplex.com/workitem/509 as for EF5), so when I added some seed data, it threw an exception

Cannot insert the value NULL into column 'primarykeycolumn', table 'tablename'; column does not allow nulls. INSERT fails.

What's really interesting is when I deleted all existing migrations and scaffolded new one from scratch, seed method ran without any problems.

So I have a question: do I need to do it any time I make changes to scheme such as adding data annotations like Identity or is there a way to save my previous migrations? Because dropping and recreating db in real-life can result in a huge data loss, which I want to avoid.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vlad Levchenko
  • 301
  • 3
  • 11
  • I believe this an issue exclusively with DatabaseGenerated data annotations. When you think about it it makes sense. How would you add an autoincremented column to existing data without essentially rebuilding the table from scratch? – Nick Bailey Mar 30 '15 at 22:17
  • Or to put it another way, if you can't do it with ALTER TABLE, then you can't do it with migrations. – Nick Bailey Mar 30 '15 at 22:19
  • 2
    You have to drop and recreate the table http://stackoverflow.com/a/18917348/150342 or build a custom migration http://romiller.com/2013/04/30/ef6-switching-identity-onoff-with-a-custom-migration-operation/ altering an identity column is not trivial – Colin Mar 31 '15 at 14:26
  • Seems to be right as changing Id column to autoincrement is really crucial change which need database recreation. Thanks for answering. – Vlad Levchenko Apr 06 '15 at 09:14

1 Answers1

0

Adding Migrations. In your Package Manager Console

Add-Migration Test1

In your Configuration.cs from Migration Class You will see Up method and Down Method. It is like Before, and After Changes. You can call them up if you want to reverse the Changes.

doing Add-Migration "NameoftheMigration" does not implement it

you need to call

Update-Database

If it tells you that there is an error, or potential Data lost.

Update-Database -Force

If you choose to use CodeFirst. You can't really Jump from Altering table by Design, then by code. You have to Choose one. As CodeFirst Migration rely on Models. Data First, Rely on Data Design.

Aizen
  • 1,807
  • 2
  • 14
  • 28
  • Changing a column between `DatabaseGenerated.None` and `DatabaseGenerated.Identity` results in a migration that does not alter the column - as described in the codeplex issue referenced in the question. So, while this is a nice description of the normal way to use migrations, it doesn't answer the question – Colin Mar 31 '15 at 14:34