Entity Framework 6 实体某些字段根据模型状态进行自动更新内容

1.定义基础实体对象

public class BaseEntity
{
  public int Id { get; set; }
  public DateTime? CreateTime { get; set; }
  public DateTime? UpdateTime { get; set; }
  public BaseEntity()
  {
    CreateTime = DateTime.Now;
  }
}

2.定义业务实体对象

public class DictEntity:BaseEntity
{
      /// <summary>
      /// 分组名称
      /// </summary>
      [StringLength(20)]
      public string GroupName { get; set; }
}

3.在DbContext类里重写SaveChanges()方法

public class DBContext : DbContext
{
        public DBContext() : base("Name=ElectronicPrescriptionDB")
        {
            Database.SetInitializer(new DBInitializer());
        }
       public DbSet<DictEntity> Dicts { get; set; }
    
public override int SaveChanges() { var selectedEntityList = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && x.State == EntityState.Modified); //可以加入cookie里面的username,比如:操作人,需扩展DateTimeEntity的属性。 //var userName = "MUKESH"; foreach (var entity in selectedEntityList) { ((BaseEntity)entity.Entity).UpdateTime = DateTime.Now; } return base.SaveChanges(); } }

之所以选择此方法,经过测试后最简便方法。其他还有:

public RepositoryContext() : base("ApiConn")
{
    ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager.ObjectStateManagerChanged += this.OnSaveChanges;
}

在OnSaveChanges(object obj, CollectionChangeEventArgs args)里面去获取实体状态,根据实体状态进行更新对应数据。但是,每次触发实体都会触发该扩展方法。所以没选择。

posted @ 2016-09-02 23:18  二先生  阅读(1641)  评论(0编辑  收藏  举报