7

Come posso ottenere uno List di tutti i DbSet in cui il tipo contenuto deriva da IncomingServiceOrderBase?Come posso trovare tutti i DbSet i cui tipi generici derivano da un determinato tipo di base?

È possibile utilizzare la riflessione per ottenere tutti i DbSet, ma come faccio a ridurli solo a quelli che contengono un tipo derivato?

Contesto

public class MyContext : DbContext 
{ 
    public DbSet<BuildingOrder> BuildingOrders { get; set; } 
    public DbSet<DeliveryOrder> DeliveryOrders { get; set; } 
    public DbSet<RetailAssemblyOrder> RetailAssemblyOrders { get; set; } 
} 

Modello

public class BuildingOrder : IncomingManufacturedProductOrderBase { } 
public class DeliveryOrder : IncomingServiceOrderBase { } 
public class RetailAssemblyOrder : IncomingServiceOrderBase { } 

risposta

18

Si può fare somehing come questo:

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; 

(questo restituisce i nomi delle proprietà; se si desidera che le istanze DbSet effettive, sostituire p.Name con p.GetValue(context, null))

2

typeof(BaseType).IsAssignableFrom(DerivedType). Restituirà vero/falso. Vedi http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx

Per attivare DbSet<T> in T (in modo da poter fare questo confronto) prendono il tipo di ogni proprietà e di fare qualcosa del genere:

public static Type GetGenericBaseType(this Type Type) { 
     if (Type == null) { 
      throw new ArgumentNullException("Type"); 
     } 
     if (!Type.IsGenericType) { 
      throw new ArgumentOutOfRangeException("Type", Type.FullName + " isn't Generic"); 
     } 
     Type[] args = Type.GetGenericArguments(); 
     if (args.Length != 1) { 
      throw new ArgumentOutOfRangeException("Type", Type.FullName + " isn't a Generic type with one argument -- e.g. T<U>"); 
     } 
     return args[0]; 
    } 
Problemi correlati