是否访问Generic类中的字段



我有4/5个表,每个表中都有相同名称的列。举个例子,Category、SubCategory和Products表都有一个名为DateCreated的列。

我目前在我的班级中有以下结构

public class Repository<T> : IRepository<T> where T : class
{
protected readonly DbContext _context = null;
private readonly DbSet<T> _entities;
public Repository(DbContext context)
{
_context = context;
_entities = _context.Set<T>();
}
public T Add(T entity)
{
return _entities.Add(entity);
}
}

使用上面的结构,我可以创建一个类别类(或任何其他(,它引用IRepository接口,并为我提供所有CRUD操作的这些方法,并传入该类型。

有没有办法使用上述通用方法,我可以设置并获得DateCreated字段,因为我需要为所有表携带一些功能,但要参考表本身,即类别或子类别等?

示例我在非通用类客户类中使用了类似的东西

public void AmendDateConflict(Customer c)
{
if (c != null)
{
nc = Get(c.Id);
if(c.DateCreated)
{
// Rest of code removed 
}
}

但正如你所看到的,c可以访问字段DateCreated,但不确定是否有方法为某些类引入相同的概念?还是保持简单,将相同的代码复制粘贴到其他类中,然后更改Type?

您可以为具有常见属性(如DateCreated(的实体创建基类。然后,您可以重写SaveChanges方法,以便在保存或更新实体时使用所需的值自动填充这些属性。

public override async Task<int> SaveChangesAsync(CancellationToken cancellationToken = new CancellationToken())
{
foreach (EntityEntry<BaseEntity> entry in ChangeTracker.Entries<BaseEntity>())
{
switch (entry.State)
{
case EntityState.Added:
entry.Entity.CreatedBy = !String.IsNullOrEmpty(_currentUserService.UserId) ? Guid.Parse(_currentUserService.UserId) : null;
entry.Entity.Created = DateTime.Now;
entry.Entity.Id = Guid.NewGuid();
break;
case EntityState.Modified:
entry.Entity.LastModifiedBy = !String.IsNullOrEmpty(_currentUserService.UserId) ? Guid.Parse(_currentUserService.UserId) : null;
entry.Entity.LastModified = DateTime.Now;
break;
}
return await base.SaveChangesAsync(cancellationToken);
}

最新更新