加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – Linq .Where(type = typeof(xxx))比较总是假的

发布时间:2020-12-15 08:23:38 所属栏目:百科 来源:网络整理
导读:我正在尝试分配静态列表 PropertyInfo Entities类中的所有DbSet属性. 但是当代码运行时,List是空的,因为.Where(x = x.PropertyType == typeof(DbSet))总是返回false. 我在.Where(…)方法中尝试了多种变体,如typeof(DbSet),Equals(…),. UNDderlyingSystemTyp
我正在尝试分配静态列表< PropertyInfo> Entities类中的所有DbSet属性.

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

我在.Where(…)方法中尝试了多种变体,如typeof(DbSet<>),Equals(…),. UNDderlyingSystemType等,但没有效果.

为什么.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是一个单独的类型,您应该使用更具体的方法:
bool IsDbSet(Type t) {
    if (!t.IsGenericType) {
        return false;
    }
    return typeof(DbSet<>) == t.GetGenericTypeDefinition();
}

现在你的Where子句看起来像这样:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读