C# 使用泛型和接口的Linq查询

C# 使用泛型和接口的Linq查询,c#,entity-framework,linq,generics,C#,Entity Framework,Linq,Generics,我有几个实体框架类,它们通过IInactive接口实现以下功能 public interface IInactive { bool inactive { get; set; } } 例如,“我的订单”类定义如下: public class Order : IInactive { [Key] [Required] public Guid orderId { get; set; } ... public bool inactive { get; se

我有几个实体框架类,它们通过IInactive接口实现以下功能

public interface IInactive
{
    bool inactive { get; set; }
}
例如,“我的订单”类定义如下:

public class Order : IInactive
{
    [Key]
    [Required]
    public Guid orderId { get; set; }
    ...
    public bool inactive { get; set; }
} 
var query = GetAllActive<Order>();
我正在尝试实现一个通用方法,该方法可以用于所有对象实体,无论它们是否实现IInactive接口。其名称如下:

public class Order : IInactive
{
    [Key]
    [Required]
    public Guid orderId { get; set; }
    ...
    public bool inactive { get; set; }
} 
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)
试一试


从T:class,IInactive的位置开始,看看它会带你去哪里。即使它不能解决这个确切的问题,您也可以跳过实现检查,并防止调用方使用不支持此检查的实体类型。编译器和运行时强制执行此检查!。谢谢,但我实际上希望能够为所有实体调用此方法,即使是那些没有实现IInactive的实体。如果类没有实现IInactive,我想返回所有记录。我有一个想法,但我必须测试它以确保它能工作。如果它有效,而你还没有答案,我会发布它。谢谢你,非常感谢。汤姆-谢谢你在第一期上成功了。这对我来说是新的。关于如何将IQueryable转换为IQueryable有什么想法吗?谢谢@BillHaack这是一个完全不同的问题公平地说,我编辑了这个问题,只包括第一期。我将为另一个问题创建第二个帖子。