【问题标题】:Linq .Where(type = typeof(xxx)) comparison is always falseLinq .Where(type = typeof(xxx)) 比较总是假的
【发布时间】:2025-11-24 21:40:01
【问题描述】:

我正在尝试为 Entities 类中的所有 DbSet 属性分配一个 static List<PropertyInfo>

但是,当代码运行时,List 是空的,因为 .Where(x => x.PropertyType == typeof(DbSet)) 总是返回 false

我在.Where(...) 方法中尝试了多种变体,例如typeof(DbSet<>)Equals(...).UnderlyingSystemType 等,但都没有奏效。

为什么在我的情况下.Where(...) 总是返回 false?

我的代码:

public partial class Entities : DbContext
{
    //constructor is omitted

    public static List<PropertyInfo> info = typeof(Entities).getProperties().Where(x => x.PropertyType == typeof(DbSet)).ToList();

    public virtual DbSet<NotRelevant> NotRelevant { get; set; }
    //further DbSet<XXXX> properties are omitted....
}

【问题讨论】:

  • DbSet != DbSet&lt;T&gt;... 我会说这就是问题所在
  • @ClaudioRedi 是的,这就是问题所在。是否有在线资源可以让我了解差异?

标签: c# linq ef-code-first


【解决方案1】:

由于DbSet 是一个单独的类型,您应该使用更具体的方法:

bool IsDbSet(Type t) {
    if (!t.IsGenericType) {
        return false;
    }
    return typeof(DbSet<>) == t.GetGenericTypeDefinition();
}

现在您的 Where 子句将如下所示:

.Where(x => IsDbSet(x.PropertyType))

【讨论】:

  • 代码中的错字:Type.GetGenericTypeDefinition 不接受任何参数。
  • @pinkfloydx33 你说得对,非常感谢!欢迎您编辑代码,尤其是当您看到这样的愚蠢错误时。