Press "Enter" to skip to content

DbContext DbSet invoke by type

When you need to get DbSet by using type;

public static IQueryable<object> Set(this DbContext _context, Type t)
{ 
    return _context.GetType().GetMethods().First(x => x.Name == "Set")
                .MakeGenericMethod(t)
                .Invoke(_context, null) as IQueryable<object>;
}

This extension would allow dbContext to get entity by type,

Type entityType = Type.GetType("YourProjectName.Namespace." + "yourEntityName");
yourContext.Set(entityType).ToList();

When you need the load navigation properties;

public static IQueryable<object> Set(this DbContext _context, Type t)
{ 
     IQueryable<object> query = _context.GetType().GetMethods()
                                        .First(x => x.Name == "Set")
                              .MakeGenericMethod(t)
                              .Invoke(_context, null) as IQueryable<object>;

    var navigations = _context.Model.FindEntityType(t)
                              .GetDerivedTypesInclusive()
                              .SelectMany(type => type.GetNavigations())
                              .Distinct();

     foreach (var property in navigations)
     {
         query = query.Include(property.Name);
     }

     return query;
}

Finds navigation properties and Include them one by one.