我有三个处理三个基类的通用存储库:
public class Entity
{
public int Id { get; set; }
}
public class Repository
{
public TEntity[] GetAll<TEntity>() where TEntity : Entity
{
return _context.Set<TEntity>.ToArray();
}
}
public class ArchiveEntity : Entity
{
public bool Deleted { get; set; }
}
public class ArchiveRepository
{
public TEntity[] GetAll<TEntity>() where TEntity : ArchiveEntity
{
return _context.Set<TEntity>.Where(x => x.Deleted == false).ToArray();
}
}
public class LogicalStorageEntity : ArchiveEntity
{
public int StorageId { get; set; }
}
public class LogicalStorageRepository
{
public int CurrentStorageId { get; set; }
public TEntity[] GetAll<TEntity>() where TEntity : LogicalStorageEntity
{
return _context.Set<TEntity>
.Where(x => x.Deleted == false)
.Where(x => x.StorageId = CurrentStorageId)
.ToArray();
}
}
有没有办法让一个存储库根据基类以不同的方式过滤实体?看起来像这样的东西:
public class Entity
{
public int Id { get; set; }
}
public class ArchiveEntity : Entity
{
public bool Deleted { get; set; }
}
public class LogicalStorageEntity : ArchiveEntity
{
public int StorageId { get; set; }
}
public class UniversalRepository
{
public TEntity[] GetAll<TEntity>() where TEntity : Entity
{
if (typeof(TEntity) is LogicalStorageEntity)
{
return _context.Set<TEntity>
.Where(x => /* how to filter by x.Deleted */)
.Where(x => /* how to filter by x.StorageId */)
.ToArray();
}
if (typeof(TEntity) is ArchiveEntity)
{
return _context.Set<TEntity>
.Where(x => /* how to filter by x.Deleted */)
.ToArray();
}
return _context.Set<TEntity>.ToArray();
}
}
编辑。问题不是关于如何检查实体是否属于特定类型。真正困难的部分是当您知道实体可以通过“已删除”或某些其他属性进行过滤时应用过滤器。由于存在 TEntity : Entity 限制,因此您无法访问 Deleted 属性。
最佳答案
您可以通过强制转换来完成此操作,但我会质疑仅执行非泛型功能的泛型方法的有用性。
我的意思是,如果没有针对多种类型执行的通用代码,那么在我看来,您实际上也可以在特定于类的派生中实现它。
关于c# 如何处理这种泛型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13801957/