How to create e.ID == id lambda expression dynamically

c# dynamic-linq lambda linq reflection


I've read many great answers here on stack about dynamic creation of lambda expression, but cannot make my own.

I need to select entity from DB by ID, but I don't know its type beforehand. Only name of a type. So:

var modelType = Assembly.Load("Models").GetTypes().First(t => t.Name == type + "Model"); 
MethodInfo method = typeof(CommonRepository).GetMethod("GetByExpression",
                           BindingFlags.Instance | BindingFlags.Public);

var arg = Expression.Constant(null, modelType);
var body = Expression.Convert(Expression.PropertyOrField(arg, "ID"),
var lambda = Expression.Lambda<Func<object, bool>>(body);

var model = method.Invoke(this, new object[] { lambda });

var field = modelType.GetProperty("Disable", BindingFlags.Instance);
field.SetValue(model, false);


I guess in my code I've made "e.ID" part of lambda. How to make "== id" part?

9/19/2017 1:22:48 PM

Accepted Answer

I try to break the expression up into its parts, using comments to help understand the expression to be built.

Consider the following...

// id
var id = 2;
var idConstant = Expression.Constant(id);
// (object e) => ...
var param = Expression.Parameter(typeof(object));
// (object e) => ((modelType)e).ID
var property = Expression.PropertyOrField(Expression.Convert(param, modelType), "ID"));
// (object e) => ((modelType)e).ID == id
var body = Expression.Equal(property, idConstant);

var lambda = Expression.Lambda<Func<object, bool>>(body, param);
9/19/2017 11:53:44 AM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow