Phil Scholtes
Phil Scholtes

Reputation: 419

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?

Upvotes: 6

Views: 9301

Answers (1)

StriplingWarrior
StriplingWarrior

Reputation: 156469

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 => ...);
}

Upvotes: 2

Related Questions