我有几个实体框架类来实现以下 IInactive 接口。
public interface IInactive
{
bool inactive { get; set; }
}
例如,我的 Order 类定义如下:
public class Order : IInactive
{
[Key]
[Required]
public Guid orderId { get; set; }
...
public bool inactive { get; set; }
}
我正在尝试实现一种通用方法,该方法可用于所有对象(实体(,无论它们是否实现 IInactive 接口。它将调用如下:
var query = GetAllActive<Order>();
我这个泛型方法的代码如下所示:
public IQueryable<T> GetAllActive<T>() where T : class
{
DbSet<T> dbSet = this._db.Set<T>();
// Does the entity implement the IInactive interface.
// If yes, only return "active" row, otherwise return all rows
if (typeof(T)is IInactive)
{
// Problem: the code in this block never executes, that is,
// (typeof(T)is IInactive) never evaluates to true
...
}
return dbSet;
}
我将非常感谢一些帮助解决这个问题!谢谢。
而不是
if (typeof(T) is IInactive)
尝试
if (typeof(IInactive).IsAssignableFrom(typeof(T)))