Entity Framework 6 Refresher: Changing a nullable field to non-nullable
2 minute read
You may not know this, but on rare occasions business rules and requirements change. Let’s consider a case where our Person class has a Weight and a Modified field.
After applying this migration, data in our database looks like this.
Let’s imagine that everything runs smoothly for several days and then all of a sudden a project manager or a process manager or a product manager calls and makes a much bigger deal than he needs to about Weight and Modified being critical. “No big deal” you think. And off to work you go to make these fields non-nullable.
In them PMC, you enter update-database and get a nice long error starting with System.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'Weight', table 'RefresherContext.dbo.People'; column does not allow nulls. UPDATE fails.. Oh. If we run update-database -script we see the following. The existing records all have null for Weight and Modified and this migration is explicitly saying that is not allowed.
No problem. We can manually update the migration to update the existing values.
The Sql method here gets us a script that looks something like this.