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));
}
}
If
tis an instance ofSystem.TypeandTis a type, you should write:Instead of: