4
votes

Here is my code:

UVCUpdate update = new UVCUpdate();
update.CurrentDate = DateTime.Now;
_context.UVCUpdates.Add(update);

_context.SaveChanges();

Now I am getting an inner exception though saying this:

Cannot insert the value NULL into column 'CurrentDate', table 'bLinked.dbo.BlackbookUpdateUVC'; column does not allow nulls. INSERT fails.

If I output the DateTime.Now just before this code it outputs:

9/15/2016 7:26:35 PM

My data type for CurrentDate in the db is set to datetime and in the class it is set to DateTime. Neither allow for nulls, but DateTime.Now should not be null right?

2
Show definition of UVCUpdate class.Mairaj Ahmad
Most likely CurrentDate has (wrongly) storage generated pattern Identity or Computed in your model, so EF just ignores whatever value is provided there. In database itself it's not identity or computed column, and requires a value.Evk
As an aside, you may wish to use datetime2. You can add this by putting this line of code in your context's override of OnModelCreating() : modelBuilder.Properties<DateTime>().Configure(c => c.HasColumnType("datetime2"));.Simon B
@Evk, wow, you guessed the problem. Go ahead and post an answer and I will accept it!Tyler
Evk was right guys, I didn't even realize it. I'm actually really surprised he was able to guess that based on the error. Like... wow.Tyler

2 Answers

1
votes

It almost always happens when there is mismatch between so called "store generated pattern" between EF model and database. If model column has store generated pattern of Identity or Computed - that means EF will be sure those values will be automatically provided by database on insert or update, and there is no need to include them in INSERT or UPDATE statements. Missing values will have default NULL value, and if this column is non-nullable in database at the same time, and is not really computed or identity - you have the error in question.

0
votes

I am sorry guys, I feel like an idiot. Thank you to Leopard.

I went to get the UVCUpdate class to show him and realized that when I copied that class from another class I accidentally left [DatabaseGenerated(DatabaseGeneratedOption.Identity)] in the class for the CurrentDate. So it was likely attempting to send a null value to the SQL so the SQL would create an ID, but the field was set to not allow nulls. CurrentDate was not supposed to be an ID so I removed that and now it works...