Linq To Entities Where Condition to Expressions比较

时间:2015-11-10 12:00:25

标签: c# entity-framework linq-to-entities expression

我有3个用Entity Framework映射的类

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

public class B
{
    public string Name { get; set; }
    public A A { get; set; }
}

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

我有这个Linq To Entities Where Condition

return queryableOfB.Where(b => b.A.Name = instanceOfC.Name);

因为这是我逻辑中的重复方法,所以我想创建一个方法:

protected void GetFilter<B, TBProperty, TCProperty>(
        IQueryable<B> queryofB, C cModel, 
        Expression<Func<B, TBProperty>> bExpression,
        Expression<Func<C, TCProperty>> cExpression)
    {
        var bExpValue = cExpression.Compile()(cModel);
        queryofB.Where(b => b.Property.EndsWith(bExpValue)); // How can I compare two expressions? but adding "for example" an .EndsWith to expression 1?
    }

重要的是不要在表达式中传递.EndsWith,因为必须在方法中使用EndsWith,StartsWith,Contains或精确比较的决定。

先谢谢大师。

1 个答案:

答案 0 :(得分:0)

实际上where方法期望函数作为谓词。你可以试试下面的一个。

它什么都不做只调用where方法。它更好地使用那里方法内联。但是告诉你如何做到这一点。

  static IEnumerable<T1> M<T1>(IEnumerable<T1> objEnumerable, Func<T1, bool> wherePredicate)
  {
      return objEnumerable.Where(predicate);
  }

  // calling like 
  var listOfBObjects = GetBObjectIEnumerable();
  C instanceOfC  = GetCClassObject();
  M<B>(listOfBObjects, b => b.A.Name = instanceOfC.Name);

<强>更新

你可以使用

  M<B>(listOfBObjects, b => b.A.Name.Equals(instanceOfC.Name));
  M<B>(listOfBObjects, b => b.A.Name.StartsWith(instanceOfC.Name));
  M<B>(listOfBObjects, b => b.A.Name.Contains(instanceOfC.Name));

提高性能和所有。是的,您可以使用IQueryable而不是IEnumerable