Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to assign a static List<PropertyInfo> of all DbSet properties in the Entities class.

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

I tried multiple variations in the .Where(...) method like typeof(DbSet<>), Equals(...), .UnderlyingSystemType, etc. but none works.

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

My code:

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....
}
like image 856
Tom Avatar asked Oct 19 '17 19:10

Tom


1 Answers

Since DbSet is 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 Where clause will look like this:

.Where(x => IsDbSet(x.PropertyType))
like image 90
Sergey Kalinichenko Avatar answered Sep 30 '22 21:09

Sergey Kalinichenko