I need to get all tables in the database using EF. I need them to go table by table and extract certain information from each. Any idea how?
The DbSet class represents an entity set that can be used for create, read, update, and delete operations. The context class (derived from DbContext ) must include the DbSet type properties for the entities which map to database tables and views. Adds the given entity to the context with the Added state.
Intuitively, a DbContext corresponds to your database (or a collection of tables and views in your database) whereas a DbSet corresponds to a table or view in your database.
Initially you find all entities whose state is not unchanged and save their entry. Then you set the state of every entity that isn't of your type TEntity and set their state to unchanged. Then call the base. SaveChanges() to save all changes to entities of your type.
Here is the extension method I use in my EntityFramework Plus library.
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;
}
}
Edit You need to use reflection from the DbSet element type and iterate over all properties. This will not work with TPC, TPT and TPH
For a simpler solution, use the method GetModel from Entity Framework Extensions. This is a FREE feature of this library.
Project: Entity Framework Extensions
Documentation: GetModel
Disclaimer: I'm the owner of the project Entity Framework Extensions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With