1

I have one expression , for example x=>x.Id ;

And I have a function, where I need to combine two expressions. I use Linqkit .

My model:

public class Model{
   Expression<Func<Entity,bool>> Expr {get;set;}
}

public Model Combine(Model input)
{
   var exp = x => input.Expr.Invoke(x) && x.Name.Contains("A");
   input.Expr = exp;
   input.Expr.Compile();
   return input;
}

Than I want to pass it in my repository, where I need to sort my entity.

public Ienumerable<Entity> Get(Model model)
{
   var entity = _context.Entity.Where(model.Expr).ToList(); // there  A cycle was detected in a LINQ expression exception
}
jack
  • 13
  • 3

1 Answers1

0

If you are not going to use Predicate builder, you should use Expand in order to create a copy with expanded sub expressions

var expandedInput = input.Expr.Expand<Func<Entity,bool>>();
var exp = x => expandedInput.Invoke(x) && x.Name.Contains("A");
input.Expr = exp.Expand<Func<Entity,bool>>();

It's a bit ugly so, use PredicateBuilder as suggested if you can (it has an implicity cast to Expression<TDelegate>)

Edit: Added first expansion (which I thought was not necessary)

Andrés Robinet
  • 1,527
  • 12
  • 18
  • sorry, but now I have that : Unable to cast object of type 'System.Linq.Expressions.PropertyExpression' to type 'System.Linq.Expressions.LambdaExpression'. in this line: input.Expr = exp.Expand>(); – jack Dec 10 '16 at 21:59
  • What do you get in this case? `var expandedInput = input.Expr.Expand>();` `var exp = x => expandedInput.Invoke(x) && x.Name.Contains("A");` `input.Expr = exp.Expand>();` – Andrés Robinet Dec 10 '16 at 22:05