1.定義基礎實體對象 2.定義業務實體對象 3.在DbContext類里重寫SaveChanges()方法 之所以選擇此方法,經過測試後最簡便方法。其他還有: 在OnSaveChanges(object obj, CollectionChangeEventArgs args)裡面去獲取實體狀態,根據 ...
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)裡面去獲取實體狀態,根據實體狀態進行更新對應數據。但是,每次觸發實體都會觸發該擴展方法。所以沒選擇。