Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Entity by Name

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?

like image 544
Phil Scholtes Avatar asked May 08 '12 19:05

Phil Scholtes


1 Answers

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 => ...);
}
like image 140
StriplingWarrior Avatar answered Oct 31 '22 17:10

StriplingWarrior