Created
July 27, 2022 11:44
-
-
Save kek-Sec/a7835de00b05c735e58d29e55f6ca4e4 to your computer and use it in GitHub Desktop.
Fetch all dbSets from a given EfCore context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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