Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework not updating column with default value

Tags:

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.

like image 835
t_plusplus Avatar asked Aug 29 '13 08:08

t_plusplus


People also ask

How do I set default value in EDMX?

edmx viewer select an entity -> go the column -> properties -> Default Value. Add the default value for the column in it and that's it.

How do you assign a value to a table column by default?

In Object Explorer, right-click the table with columns for which you want to change the scale and select Design. Select the column for which you want to specify a default value. In the Column Properties tab, enter the new default value in the Default Value or Binding property.

How does Entity Framework update data?

Update Objects in Entity Framework 4.0First retrieve an instance of the entity from the EntitySet<T> (in our case ObjectSet<Customer>), then edit the properties of the Entity and finally call SaveChanges() on the context.


1 Answers

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?

like image 150
mattmanser Avatar answered Oct 02 '22 13:10

mattmanser