Combining multiple expressions to dynamically create select expression containing expressions as getters
Asked Answered
P

0

2

Given an input of two expressions, e.g.:

Expression<Func<Customer,string>> nameExpression = x=>x.Name;
Expression<Func<Customer,string>> nameExpression = x=>x.MarketSegment.Name;

and a

IQueryable<Customer> query = ..//fetch from dbContext;

I want to dynamically create an expression that selects these properties from the query.

the end result would have to execute as follows:

Expression<IQueryable<Customer>,IQueryable<dynamic>> query = query.Select(x=>new{
  x=>x.Name,
  x=>x.MarketSegment.Name
});

I figured out that Expression.New could be an option in this question, but I'm unable to figure out how to pass expressions to it.

Parsee answered 2/12, 2016 at 13:29 Comment(4)
maybe this helps: Combine several similar SELECT-expressions into a single expressionVilberg
Thanks, I managed to get it working using an expression visitor to bind x from the query select to the x parameter in the body of the expressions passed as an input. I'll try to post an in-depth answer with some code samples later on, when we cleaned it all up.Parsee
Hey @MichielCornille, can you post your code samples please? Thanks!Deformed
It was 2 years ago, I no longer work at the closed-source company I wrote this for. Sorry!Parsee

© 2022 - 2024 — McMap. All rights reserved.