Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use database default for CreatedDate column in EF code-first 4.3?

I'd like to have a CreatedDate column in my Accounts table, defined as follows:

CreatedDate DATETIME NOT NULL DEFAULT GETUTCDATE()

This will map to a CreatedDate property in the class:

public class Account
{
    public DateTime? CreatedDate { get; private set; }
    // ... other properties ...
}

When creating a new account, I'd like to leave CreatedDate set to NULL, and let the database fill it in. When loading an existing account from the DB, I'd like EF to retrieve the database-generated CreatedDate.

I'm using EF 4.3 code-first with explicit migrations. When EF generated a migration for the Accounts table, I modified it as follows:

CreatedDate = c.DateTime(nullable: false, defaultValueSql: "GETUTCDATE()"),

Unfortunately, when I try to map the table using EF 4.3, EF attempts to insert the value NULL in the CreatedDate column.

I tried setting DatabaseGeneratedOption.Identity for the property, as suggested by Ladislav Mrnka. However, this removes the identity option from the primary key property. I tried using DatabaseGeneratedOption.Computed instead, but it continues to try to insert a NULL. I reverted all migrations and reran them - the problem still occurs.

Here is what I'm doing in OnModelCreating:

modelBuilder.Entity<Account>().Property(a => a.CreatedDate)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

Does anyone have any suggestions?

Thanks for your help,
Richard

like image 308
Richard Beier Avatar asked Oct 07 '22 18:10

Richard Beier


1 Answers

Make your date non nullable in your entity or nullable in your database. Database default value is used only if insert statement doesn't send explicit value. In case of EF this happens only if you mark your CreatedDate with DatabaseGeneratedOption.Identity. If it removes default identity from your primary key force it manually through data annotations or fluent API.

like image 198
Ladislav Mrnka Avatar answered Oct 12 '22 10:10

Ladislav Mrnka