我有一个名为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());
}
}
答案 0 :(得分:0)
首先:您可能不应该有两个存储库。 EF已经是具有称为DbContext的UoW的通用存储库。进一步了解here。
如果您可以等到调用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();
}