3

I want to use expression trees to make filters with entity framework.

So this is my types

public class Type1
{
    public string Name { get; set; }
}

public class Type2
{
    public IEnumerable<string> Names { get; set; }
}

and this is my specification

public Expression<Func<Entities.Type1, bool>> MyExpression(Type2 filter)
{
    //something like where name in (name[0], name[1], ... name[n])
}

I need transform this in something like Sql where in.

How can I do it, and what's the best form?

How can I make Entity Framework understand my arbitrary expression in the way I want?

Jedi31
  • 735
  • 1
  • 6
  • 22

2 Answers2

3

You can do it simply like this:

public Expression<Func<Type1, bool>> MyExpression(Type2 filter)
{
    return x => filter.Names.Contains(x.Name);
}
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
1

You can try this:

public Expression<Func<Type1, bool>> MyExpression(Type2 filter)
{
    Expression<Func<Type1, bool>> expression =  t1 => filter.Names.Contains(t1.Name);
    return expression;
}

In this post you can find good explanation why you can convert a lambda expression to an expression tree.

Community
  • 1
  • 1
ocuenca
  • 38,548
  • 11
  • 89
  • 102