Entity Framework 6 w/ DatabaseGeneratedOption.Computed: column does not allow nulls. INSERT fails

c# calculated-columns entity-framework entity-framework-6 sql-server

Question

Entity Framework 6 with a Database Generated field is failing on insert. From what I've read once you mark a column as DatabaseGenerated, EF won't try to insert/update anything into that field, which is especially important in my case because the fields on the database are SQL Server computed columns and not just default values, which is what I've seen in a lot of similar questions on Stack Overflow/Google.

Column definition (using a User Defined Function in the computed column):

ALTER TABLE dbo.MyModel ADD [TotalUnits]  AS ([dbo].[CalculateTotalUnits]([Id]));

EF definition:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public decimal TotalUnits { get; private set; }

And then I'm just doing a

var myNewModel = new MyModel();
DbContext.MyModels.Add(myNewModel);
DbContext.SaveChanges();

Which gives:

System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'TotalUnits', table 'MyDatabase.dbo.MyModel'; column does not allow nulls. INSERT fails.

Why is EF trying to insert a NULL value into a computed column, and how can I tell it not to?

1
2
7/3/2017 7:28:45 PM

Accepted Answer

Turns out when running integration tests EF was configured to use Automatic Migrations instead of our own migrations. Since the computed columns were being added in a custom SQL script during the Up method of a migration, the columns weren't actually computed columns during the tests but were in fact generated by EF as regular decimal (non-nullable) fields. Thus trying to add a new model to the context was causing EF to insert NULL into those columns and blowing up.

Solution is to actually run the migrations in the integration tests. Once the column is actually computed than EF stops tracking it.

1
7/10/2017 6:48:19 PM


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