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
}
}
}
}