如何找到其泛型类型派生自给定基类型的所有DbSet?

Ben*_*min 8 c# generics reflection entity-framework entity-framework-4.1

如何获取List所包含类型派生的所有DbSet IncomingServiceOrderBase

我可以使用反射来获取所有DbSet,但是如何将其过滤到包含派生类型的那些?

上下文

public class MyContext : DbContext
{
    public DbSet<BuildingOrder> BuildingOrders { get; set; }
    public DbSet<DeliveryOrder> DeliveryOrders { get; set; }
    public DbSet<RetailAssemblyOrder> RetailAssemblyOrders { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

模型

public class BuildingOrder : IncomingManufacturedProductOrderBase { }
public class DeliveryOrder : IncomingServiceOrderBase { }
public class RetailAssemblyOrder : IncomingServiceOrderBase { }
Run Code Online (Sandbox Code Playgroud)

Tho*_*que 20

你可以这样做:

var sets =
    from p in typeof(MyContext).GetProperties()
    where p.PropertyType.IsGenericType
    && p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>)
    let entityType = p.PropertyType.GetGenericArguments().First()
    where typeof(IncomingServiceOrderBase).IsAssignableFrom(entityType)
    select p.Name;
Run Code Online (Sandbox Code Playgroud)

(这将返回属性的名称;如果您想要实际的DbSet实例,请替换p.Namep.GetValue(context, null))