我有三个处理三个基类的通用存储库:
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();
}
}
编辑。问题不是关于如何检查实体是否属于特定类型。真正困难的部分是当您知道实体可以通过 Deleted 或其他属性过滤时应用过滤器。由于存在限制 TEntity : Entity ,因此您无法访问 Deleted 属性。