Im trying to write a query function. And with expression trees I am trying to get runtime input to query.
var query = context.Customers
.Join(context.Orders,
customer => customer.CustomerId,
order => order.CustomerId,
(customer, order) => new
{
customer.ContactName,
order.ShipCountry
}).Where(customer => customer.ContactName.StartsWith("A"))
.ToList();
I created a simple query. Then tried to functionalize it using expression trees:
public static IEnumerable<object> GetContactNameandOrderDate(string prop_1, string prop_2, string prop_3, string text)
{
NorthwindContext context = new();
var customer = Expression.Parameter(typeof(Customer)); //customer
var order = Expression.Parameter(typeof(Order)); //order
var customerCustomerId = Expression.PropertyOrField(customer, prop_1); //customer.CustomerId
var orderCustomerId = Expression.PropertyOrField(order, prop_1); //order.CustomerId
var customerContactName = Expression.PropertyOrField(customer, prop_2); //customer.ContactName
var orderShipCountry = Expression.PropertyOrField(order, prop_3); //order.ShipCountry
var textConstant = Expression.Constant(text); //"A"
Expression<Func<Customer, int>> lambda_1 = Expression.Lambda<Func<Customer, int>>(customerCustomerId, customer); //customer => customer.CustomerId
Expression<Func<Order, int>> lambda_2 = Expression.Lambda<Func<Order, int>>(orderCustomerId, order); // order => order.CustomerId
Expression startsWith = Expression.Call( //customer.ContactName.StartsWith("A"))
customerContactName,
typeof(String).GetMethod("StartsWith",
new Type[] { typeof(String) }), textConstant );
Expression<Func<Customer, bool>> lambda_3 = Expression.Lambda<Func<Customer, bool>>(startsWith, customer); //customer => customer.ContactName.StartsWith("A"))
var values = context.Customers.Join(context.Orders, lambda_1, lambda_2, (customer, order) => new { customerContactName, orderShipCountry }).Where(lambda_3).ToList(); //lambda_3 error
return values;
}
Im getting error at the Where(lambda_3)
that says:
Error CS1503 Argument 2: cannot convert from 'System.Linq.Expressions.Expression<System.Func<expression_trees.Entities.Customer, bool>>' to 'System.Func<<anonymous type: System.Linq.Expressions.MemberExpression customerContactName, System.Linq.Expressions.MemberExpression orderShipCountry>, bool>'
Im guessing I did something wrong writing customer.ContactName.StartsWith("A"))
as expression. But I could not figure out what is wrong.
I am essentially trying to figure out if I can use expression trees effectively and dynamic with entity framework. Like getting database objects that has "/" at the beggining in runtime. Is my approach wrong? How can i use expression trees effectively with entity framework? I could not find many resource on this topic so any recommendation would be helpful.