开发者

CreatedDate and AmendDate generated by the database

User class:

public class User
{
    public DateTime CreatedDate { get; private set; }
    public DateTime? AmendDate { get; private set; }
}

I need the columns CreatedDate and AmendDate have the values ​​generated by the database (now() command)

Reading some articles on the internet, advised 开发者_如何学Gome to use this in DbContext class on OnModelCreating method:

Property(p => p.CreatedDate)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

Property(p => p.AmendDate)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);

But does not work, saying that an error is supported types are rowversion and timespan.

How do you do with these property types?

Any tips?


You can make both columns nullable and Save changes with both columns with null values. You also need set the default value for the column as getdate() in the relevant column in the database. Then these columns will automatically be populated with current date if you try to insert null values. But EF will not update the property with the database generated date value.

Other solution is to set the values before you call the SaveChanges() method

public override int SaveChanges()
{
    var changeSet = ChangeTracker.Entries<User>();

    if (changeSet != null)
    {
        foreach (var entry in changeSet
       .Where(c => c.State == EntityState.Added || c.State == EntityState.Modified))
        {
            entry.Entity.CreatedDate = entry.Entity.AmendDate = DateTime.Now;
        }
    }
    return base.SaveChanges();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜