Linq.Where (type = typeof (xxx)) comparison is always incorrect

I am trying to assign static List<PropertyInfo>all the DbSetproperties in a class Entities.

However, when the code starts, List is empty because it .Where(x => x.PropertyType == typeof(DbSet)) always returns false .

I tried a number of options .Where(...), such as typeof(DbSet<>), Equals(...), .UnderlyingSystemType, etc., but does not work.

Why .Where(...)does it always return false in my case?

My code is:

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....
}
+6
source share
1 answer

Since it DbSetis a separate type, you should use a more specific approach:

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

Now your suggestion Wherewill look like this:

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

All Articles