Is there an easy way to make EntityFramework use SQL default values?

前端 未结 3 1750
轻奢々
轻奢々 2020-12-03 17:23

For example, most of my entities have DateCreated and DateModified fields. The defaults to these are set to GetUtcDate() in SQL Server.

If I try and create an entity

3条回答
  •  无人及你
    2020-12-03 18:01

    One solution is to override your generated entitycontext class by using partial. This will intercept inserts/updates on all the entity classes in your EF context:

    public partial class MyEntities : ObjectContext
    {
        public override int SaveChanges(SaveOptions options)
        {
            this.DetectChanges();
    
            foreach (var insert in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Added))
            {
                if (insert.Entity.HasProperty("DateCreated"))
                    insert.Entity.GetType().GetProperty("DateCreated").SetValue(insert.Entity, DateTime.UtcNow, null);
                if (insert.Entity.HasProperty("LastModified"))
                    insert.Entity.GetType().GetProperty("LastModified").SetValue(insert.Entity, DateTime.UtcNow, null);
            }
    
            foreach (var update in this.ObjectStateManager.GetObjectStateEntries(System.Data.EntityState.Modified))
            {
                if (update.Entity.HasProperty("LastModified"))
                    update.Entity.GetType().GetProperty("LastModified").SetValue(update.Entity, DateTime.UtcNow, null);
            }
    
            return base.SaveChanges(options);
        }
    }
    

    Or do something similar, looking for inserts/updates on your datestamp fields and removing them from the ObjectStateEntries collection?

提交回复
热议问题