How to use Reflection in linq queries ? RRS feed

  • Question

  • User-79977429 posted


    I'm looking for a way to use reflection in my linq queries to increase code reusability. for example, i want to change this method :

    private Orders GetObjectGraph(MyDbContext dbContext, int orderID)
    	return dbContext.Orders.Include(o => o.OrderDetails).AsNoTracking().FirstOrDefault(o => o.OrderID == orderID);

    To something like this :

    private object GetObjectGraph(MyDbContext dbContext, string masterEntityName, string detailsEntityName, string masterFieldName, object masterFieldValue)
    	return dbContext[masterEntityName].Include(o => o[detailsEntityName]).AsNoTracking().FirstOrDefault(o => o.[masterFieldName] == masterFieldValue);

    Can anybody help me how to accomplish this task ?

    Thanks in advance

    Sunday, May 31, 2020 8:31 PM

All replies

  • User1120430333 posted

    Can anybody help me how to accomplish this task ?

    Using Reflections with Linq? IMHO, it's not an optimal choice nor a good idea. 

    Sunday, May 31, 2020 10:01 PM
  • User-474980206 posted

    you use reflection to get the entity

    var entity = dbContext.GetType().GetProperty(propName).GetValue(dbContext, null) as IQuerayable;

    then you build an expression tree for the include parameter:


    then you again use reflection to call the .Include() passing the expression tree.

    Monday, June 1, 2020 3:32 PM
  • User-79977429 posted

    Thanks for reply

    Can u provide full description (with code) for my code?

    Thanks in advance

    Monday, June 1, 2020 3:37 PM