24

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.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
t_plusplus
  • 4,079
  • 5
  • 45
  • 60
  • I guess this should help you http://www.ladislavmrnka.com/2011/03/the-bug-in-storegeneratedpattern-fixed-in-vs-2010-sp1/ – V4Vendetta Aug 29 '13 at 08:47
  • The highest rated answer here may help: http://stackoverflow.com/questions/14385477/adding-createddate-to-an-entity-using-entity-framework-5-code-first (may not). – Chris Aug 29 '13 at 08:51

6 Answers6

18

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?

Community
  • 1
  • 1
mattmanser
  • 5,719
  • 3
  • 38
  • 50
2

Just apply the [DatabaseGenerated(DatabaseGeneratedOption.Identity)] attribute to on the column field in your entity object definition.

For example:

public class SomeTable
{
    ...

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

    ...
}

This tells the Entity Framework that your column's initial value is supplied by the database. The value will update automatically from the database after row insertion.

kkahl
  • 415
  • 5
  • 17
  • Not working for me - I have three default values in my table (`NEWID()`, `SYSTEM_USER`, and `GETDATE()`), I marked each of these fields with `[DatabaseGenerated(DatabaseGeneratedOption.Identity)]`, and I get the error `Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.`. – alex Sep 09 '16 at 16:03
  • You'll, of course, want to get into the debugger and have a look at the extra information attached to the exception (in the EntityValidationErrors property). It's possible that EntityFramework is simply failing to parse/understand one of the column values. My experience suggests you may want to try adding these one at a time to find the culprit. I'm also guessing it's most likely related to the date column, which should be supportable but may be hard to get right since there are so many date formats and structures available in the mix. – kkahl Oct 14 '16 at 23:19
  • While you are on the right track here, the correct answer is @CptRobby 's answer using the data annotation: [DatabaseGenerated(DatabaseGeneratedOption.Computed)] – HostMyBus May 17 '17 at 10:53
  • Yeah, a `DateTime` column as identity column is highly uncommon. – Gert Arnold May 11 '21 at 13:57
2

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.

CptRobby
  • 1,441
  • 15
  • 19
0

try to use this.

public virtual DateTime CreatedDate { get; set; } = new Datetime();
0

You can set StoreGeneratedPattern to Computed (as Malcolm suggested) in the GUI of the entity data model as well.

Open your .edmx file in Visual Studio Open the properties of the field (click on the field -> hit F4 or right-click->properties) Set StoreGeneratedPattern to Computed in the properties window as shown below:

Entity Framework - default values doesn't set in SQL server table

Peyman Majidi
  • 1,777
  • 2
  • 18
  • 31
İpek
  • 1
  • 3
-1

To get to work i declared a new variable and set that variable to the current time. Then when inserting the data i referenced the variable to the column:

var db = new YourTableEntities();
var dateNow = DateTime.Now; 

db.YourTableEntities.Add(new YourTableEntities()
{
    ColumnAInTable = someAVariable,
    ColumnBInTable = someBVariable,
    ColumnThatShouldDefaultToGetDate = dateNow
});

Hope this helps!

Shaheen K
  • 124
  • 1
  • 7