Nuances when working with EF migrations

This article is not intended to be a guide to working with EF migrations. There will be no information on how to create them here. Here I have collected a few slippery points and attempts to get around them. Let's start!





Start migrations at application launch

Are you familiar with the following code?





context.Database.Migrate();
      
      



If so, most likely you roll migrations automatically at the start of the project. Good or bad, you can discuss in the comments. I, in turn, want to warn against the following.





cmd, PS , , 2 : . - , . - , (sln). .





? , ( ) . , , , , , , . ? , . , , , , , Remove-Migration, , , . , , Remove-Migration. , , ?





, 2 :









  1. .





, . .





-, :





  1. , .





  2. , , .





, Remove-Migration. , . Remove-Migration (csproj). , , , Git ( ) .





, ( ). csproj .





SQL

, , (, , - ) SQL . Script-Migration. . . .





EF Core 3.0 Script-DbContext .





, , , , SQL .





Nute here, it would seem, is simple. We change something in essence, create migration, rejoice at the result. However, the result may be unexpected when you need to delete one field and create another of the same type. In this case, the migrator will create a command to rename the column in the database. All data from the deleted column, respectively, will be transferred to the new one. In this case, you can create 2 migrations: to delete a column and to create a new one. After that, so that 2 migrations are not looming instead of one, you can combine their Up and Down codes and delete the last one.





Conclusion

In conclusion, I want to say, be attentive to the data, check new migrations, think about them, do not be afraid to edit them. And you will still step on any non-obvious rake when working with EF.








All Articles