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