ProfK
ProfK

Reputation: 51084

How can I query by property type rather than type name using LINQ?

I have the following DbContext, where each DbSet marked with a // This comment is a potential target for my GetDbSetsByType method. How can I query on actual type in my .Any lambda rather than type name? When I use t => t is T it always fails. I assume this is because the lambda parameter is declared as Type.

public class CtsDbContext : DbContext
{
    public DbSet<Gender> Genders { get; set; } // This.
    public DbSet<JobLevel> JobLevels { get; set; } // This.
    public DbSet<Country> Countries { get; set; } // This.

    public IEnumerable<DbSet<T>> GetDbSetsByType<T>() where T : class
    {
        // Get one of the above DbSets based on its type.
        var tName = typeof (T).Name;
        var props = GetType().GetProperties()
            .Where(p => p.PropertyType.IsGenericType && p.PropertyType.Name.StartsWith("DbSet"))
            .Where(p => p.PropertyType.GetGenericArguments().Any(t => t.Name == tName));
        return props.Select(p => (DbSet<T>)p.GetValue(this, null));
    }
}

Upvotes: 1

Views: 136

Answers (1)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 263047

If t is an instance of System.Type and T is a type, you should write:

t => t == typeof(T)

Instead of:

t => t is T

Upvotes: 2

Related Questions