1

I have to dynamically select from an arbitrary table :

IEnumerable<object> table = typeof(MyContext).GetProperty(tblName).GetValue(context, null) as IEnumerable<object>;

But now there is 1 more problem, I can't seem to find a way to include the related entities into the dynamic table above :

string relations= "relatedentity1,relatedentity2,relatedentity3"
relatedEntities = relations.Split(',');
foreach (string relatedEntity in relatedEntities)
{
    (table as ObjectQuery<object>).Include(relatedEntity); // error line
}

This approach is giving me this error (the table object is not null) :

Object reference not set to an instance of an object.

Normally, this is how it's done :

MaterialStartingBalance = (from a in context.MaterialStartingBalance
    .Include("Warehouse")
    .Include("Account")
    .Include("Material")
    .Include("SalesOrder")
     select a).ToList();

How do I achieve this? Thanks alot!

NeedAnswers
  • 1,411
  • 3
  • 19
  • 43
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Yuval Itzchakov Nov 17 '14 at 12:26
  • @YuvalItzchakov It really isn't. Wait I'm gonna think of some way to re-edit the question to avoid confusions – NeedAnswers Nov 17 '14 at 12:28
  • You're getting a `NullReferenceException` because there seems to be no conversion between `IEnumerable` and `ObjectQuery`. That's why your `as` statement fails. – Yuval Itzchakov Nov 17 '14 at 12:30
  • @YuvalItzchakov I edited the question, I wasn't really asking about the error, I'm trying to find the solution! – NeedAnswers Nov 17 '14 at 12:31
  • What is the concrete type of your table? – Yuval Itzchakov Nov 17 '14 at 12:33
  • @YuvalItzchakov a table class represents an entity? I don't really understand your question. can you elaborate – NeedAnswers Nov 17 '14 at 12:35
  • This: `table = typeof(MyContext).GetProperty(tblName).GetValue(context, null)` uses reflection to get a property inside your `MyContext` class. What is the concrete type of that property? – Yuval Itzchakov Nov 17 '14 at 12:36
  • @YuvalItzchakov `MyContext` is the DbContext (the database), the `property` you mentioned is an entity(a table in the database), which is a class in Entity Framework. – NeedAnswers Nov 17 '14 at 12:38
  • @YuvalItzchakov and could you remove the duplicate warning please? Thanks! – NeedAnswers Nov 17 '14 at 12:42

0 Answers0