1

I have a problem regarding on how to iterate over all the tables/DbSet in EF6 (not EF Core 6) code first.

I have these DbSet examples:

public partial class ApplicationDbContext : DbContext
{
    public ApplicationDbContext() : base(AppHelper.ConnectionString())//"name=cn"
    {
        this.Configuration.LazyLoadingEnabled = false;
    }        

    public virtual DbSet<Function> Functions { get; set; }
    public virtual DbSet<Role> Roles { get; set; }
    public virtual DbSet<User> Users { get; set; }
}

Then in my Winforms app, I did find some example from Stackoverflow which I revised the below code to loop all the table or Dbset. Please I need your help on how do I call and get the value of columns using the GetValue() method shown below:

private void Form_Load(object sender, EventArgs e)
{
    var myEntityModel = new ApplicationDbContext(); //your context
    var dbSets = myEntityModel.GetType().GetProperties().Where(p => p.PropertyType.Name.StartsWith("DbSet")); //get Dbset<T>            

    foreach (var dbSetProps in dbSets)
    {                
        var dbSet = dbSetProps.GetValue(myEntityModel, null);
        var dbSetType = dbSet.GetType().GetGenericArguments().First();                
        BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
        PropertyInfo[] properties = dbSetType.GetProperties(flags);

        foreach (PropertyInfo prop in properties)
        {
            var type = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;

            if (type == typeof(DateTime))
            {
                // DateTime DataType
                Console.WriteLine("Name: " + prop.Name + ", Value: " + prop.GetValue(, null)); //<-- This is my problem what should i put here
            }
            else
            {
                // Not a DateTime DataType
                Console.WriteLine("Name: " + prop.Name + ", Value: " + prop.GetValue( , null));//<-- This is my problem what should i put here
            }
        }
    }
}
Caius Jard
  • 72,509
  • 5
  • 49
  • 80
Jam Godz
  • 11
  • 4

1 Answers1

0

With this code, you'll get all of tables in DB

var tableNames = context.Model.GetEntityTypes()
    .Select(t => t.GetTableName())
    .Distinct()
    .ToList();

then iterate over the tables and get individual table info

foreach(var tableName in tableNames  {
    
    var tableType = _dbContext.Model.GetEntityTypes().First(c => c.GetTableName() == tableName);
        foreach (var property in tableType.GetProperties())
        {
            var type = property.ClrType;
            var typeName = type.ShortDisplayName();
        }
    }
Asif Rahman
  • 225
  • 2
  • 13