Say I have a list of EF entity names like:
List<string> entityNames = new List<string>(){
"Table1",
"Table2",
"Table3"
};
From this list of entities I want to query each entity individually, similar to:
var result = efContext.Table1.Where(t => ...);
Using reflection, or black magic, how would I obtain a reference to the actual entity so that I could wind up with something like:
foreach(var e in entityNames)
{
var entity = efcontext.GetType().GetProperties().Where(t => t.Name == e).Single();
var result = efContext.entity.Where(t => ...);
}
Thoughts?
Supposing that all of the Entity types listed implement some common interface that you intend to use in your Where
clause, you could do something like this:
foreach(var e in entityNames)
{
PropertyInfo entityProperty = efcontext.GetType().GetProperties().Where(t => t.Name == e).Single();
var baseQuery = (IQueryable<IMyEntity>)entity.GetValue(efContext, null);
var result = baseQuery.Where(t => ...);
}
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