[英]Configure automatic update of base class properties whenever derived class is updated EF Core 2.0
我有一个名为EntityBase的基类,该基类用于此项目中建模的每个实体。 该基类使用存储库模式对这些实体执行操作,如下所示。
public class Repository : IRepository
{
private readonly EfCoreContext _dbContext;
public Repository(EfCoreContext dbContext)
{
_dbContext = dbContext;
}
public IQueryable<T> All<T>() where T : EntityBase
=> _dbContext.Set<T>().AsQueryable();
public IEnumerable<T> Filter<T>(Expression<Func<T, bool>> predicate) where T : EntityBase
=> Filter<T>(predicate).AsQueryable<T>();
...
...
public T Add<T>(T entity) where T : EntityBase
{
_dbContext.Set<T>().Add(entity);
_dbContext.SaveChanges();
return entity;
}
}
这是基类
public abstract class EntityBase
{
public EntityBase()
{
this.CreatedOn = DateTime.Now;
this.UpdatedOn = DateTime.Now;
this.CreatedBy = "DC";
this.UpdatedBy = "DC";
}
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
public DateTime CreatedOn { get; set; }
public DateTime UpdatedOn { get; set; }
public int ID { get; set; }
}
每当更新任何一个派生类时,如何使用Fluent API或数据注释自动捕获EntityBase的UpdatedOn和UpdatedBy属性?
这是我的DbContext
public class EfCoreContext : DbContext
{
public EfCoreContext(
DbContextOptions<EfCoreContext> options)
: base(options) {}
public DbSet<Book> Books { get; set; }
public DbSet<Author> Authors { get; set; }
public DbSet<Order> Orders { get; set; }
protected override void
OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new BookConfig());
modelBuilder.ApplyConfiguration(new BookAuthorConfig());
modelBuilder.ApplyConfiguration(new OrderConfig());
modelBuilder.ApplyConfiguration(new LineItemConfig());
}
}
第一:您可能不应该有两个存储库。 EF已经是具有称为DbContext的UoW的通用存储库。 在此处了解更多信息。
如果您可以等到SaveChanges
被调用,则可以覆盖DbContext的SaveChanges
方法:
public override int SaveChanges()
{
var entries = ChangeTracker.Entries().Where(x => x.Entity is EntityBase && (x.State == EntityState.Added || x.State == EntityState.Modified));
foreach (var entry in entries)
{
var entity = (EntityBase)entry.Entity;
//do something
}
return base.SaveChanges();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.