Tom
Tom

Reputation: 523

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....
}

Upvotes: 6

Views: 395

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726889

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))

Upvotes: 7

Related Questions