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

Viewed 35368

I have a Date column in table which has default value or binding as getutcdate(). I want to use this in entity framework.On generating EDM I was able to find "Default Value " property at column level but I think it is for hardcoded value.

Please let me know how can I use default value specified in database.

9 Answers

StoreGeneratedPattern = "Computed" is not the same as a default value, because this property would be updated EVERY TIME with the default value in the database.. meaning it is impossible to update it manually.

You can set the StoreGeneratedPattern to Identity, in which case EF reads the value returned from the database after executing the INSERT statement. The problem with this approach is that the next time the XML mapping is generated, your change will be lost.

Another way to do it is to set the value yourself in your code to DateTime.UtcNow. You could set this in your entity's constructor (define a new constructor if necessary), or you could set it in your own event handler for your context's SavingChanges event (see How to: Execute Business Logic When Saving Changes (Entity Framework) for an example of handling the SavingChanges event).

Insert thats format:

    //class
    [Column("guid")]
    [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
    public string guid_ { get; set; }
    ...
    //end class

after the command yourContext.SaveChanges();

You can see return default data from database in your class model.

Good Look

Related