我想使用表达式树来使用实体框架制作过滤器。
所以这是我的类型
public class Type1
{
public string Name { get; set; }
}
public class Type2
{
public IEnumerable<string> Names { get; set; }
}
这是我的规范
public Expression<Func<Entities.Type1, bool>> MyExpression(Type2 filter)
{
//something like where name in (name[0], name[1], ... name[n])
}
我需要在像Sql这样的东西中进行转换。
我该怎么做,以及最好的形式是什么?
如何让Entity Framework以我想要的方式理解我的任意表达?
答案 0 :(得分:3)
你可以这样做:
public Expression<Func<Type1, bool>> MyExpression(Type2 filter)
{
return x => filter.Names.Contains(x.Name);
}
答案 1 :(得分:1)
你可以试试这个:
public Expression<Func<Type1, bool>> MyExpression(Type2 filter)
{
Expression<Func<Type1, bool>> expression = t1 => filter.Names.Contains(t1.Name);
return expression;
}
在这个post中,你可以找到很好的解释,为什么你可以将lambda表达式转换为表达式树。