EntityFramework not updating column with default value

c# entity-framework sql sql-server

Question

I am inserting an object into a SQL Server db via the EntityFramework 4 (EF). On the receiving table there is a column of (CreatedDate), which has its default value set to getdate(). So I do not provide it to the EF assuming its value will be defaulted by SQL Server to getdate().

However this doesn't happen; instead EF return a validation error n SaveChanges().

Is there any reason that you know for this happening? Please let me know.

Many thanks.

1
22
8/29/2013 8:43:47 AM

Accepted Answer

If you never want to edit that value (like with a created date), you can use:

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public virtual DateTime CreatedDate { get; set; }

This will tell the Entity Framework that the value is controlled by the database, but will still fetch the value.

Note that you then cannot change that value, so it's not a solution if you simply want an initial value.

If you just want a default value but are still allowed to edit it, or you are using the Entity Framework 5 and below, you have to set the default in code.

More discussion about this here:

How to use Default column value from DataBase in Entity Framework?

14
5/23/2017 10:31:37 AM

Popular Answer

The correct answer to this issue is to tell Entity Framework that the column is Computed.

[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public virtual DateTime CreatedDate { get; set; }

DatabaseGeneratedOption.Computed means that it is set by the database and can not be changed by Entity Framework. DatabaseGeneratedOption.Identity means that the column is an IDENTITY column, which should only used for autoincrementing numeric primary keys.

**Note that the documentation for the DatabaseGeneratedOption enumeration doesn't mention anything about IDENTITY columns (partly because that is a SqlServer specific implimentation detail). Instead it defines the Identity option as "The database generates a value when a row is inserted." I was actually looking for a way to allow a ModDate to be set using a DEFAULT constraint when the record is created, but to allow it to be modified from Entity Framework when updating the record. So because of the description, I thought I might have found a solution, but trying to modify the ModDate of a record when it was flagged with DatabaseGeneratedOption.Identity threw an exception. So no luck there.



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