Skip to content

Instantly share code, notes, and snippets.

@kek-Sec
Created July 27, 2022 11:44
Show Gist options
  • Select an option

  • Save kek-Sec/a7835de00b05c735e58d29e55f6ca4e4 to your computer and use it in GitHub Desktop.

Select an option

Save kek-Sec/a7835de00b05c735e58d29e55f6ca4e4 to your computer and use it in GitHub Desktop.
Fetch all dbSets from a given EfCore context
using (var ctx = new TestContext())
{
var dbSetProperties = ctx.GetDbSetProperties();
List<object> dbSets = dbSetProperties.Select(x => x.GetValue(ctx, null)).ToList();
}
public static class Extensions
{
public static List<PropertyInfo> GetDbSetProperties(this DbContext context)
{
var dbSetProperties = new List<PropertyInfo>();
var properties = context.GetType().GetProperties();
foreach (var property in properties)
{
var setType = property.PropertyType;
#if EF5 || EF6
var isDbSet = setType.IsGenericType && (typeof (IDbSet<>).IsAssignableFrom(setType.GetGenericTypeDefinition()) || setType.GetInterface(typeof (IDbSet<>).FullName) != null);
#elif EF7
var isDbSet = setType.IsGenericType && (typeof (DbSet<>).IsAssignableFrom(setType.GetGenericTypeDefinition()));
#endif
if (isDbSet)
{
dbSetProperties.Add(property);
}
}
return dbSetProperties;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment