Lambda表达式 - 使用实体框架Include()和任何操作?

时间:2012-11-02 07:01:58

标签: lambda entity-framework-5

以下代码正在运作

var queryResults = _db.Projects
           .Include("Participants.Person")
           .Where(Project => Project.Participants.Any(Parti => Parti.Person.FirstName == "test3"));

我正在动态构建lambda表达式。为了实现上述目标,我必须编写大量代码。

我想实现以下目标。

var queryResults = _db.Projects
           .Include("Participants.Person")
           .Where(Project => Project.Participants.Person.FirstName == "test3"));

任何建议请分享。

以下编辑部分

我正在尝试任何操作。但我在这一行得到例外。有什么建议吗?

MemberExpression propertyOuter = Expression.Property(c,“Participant”);

ParameterExpression tpe = Expression.Parameter(typeof(Participant), "Participant");
Expression left1 = Expression.Property(tpe, typeof(Participant).GetProperty("Person"));
Expression left2 = Expression.Property(left1, typeof(Person).GetProperty("FirstName"));
Expression right1 = Expression.Constant(filter.FieldValue);
Expression InnerLambda = Expression.Equal(left2, right1);
Expression<Func<Participant, bool>> innerFunction = Expression.Lambda<Func<Participant, bool>>(InnerLambda, tpe);

MethodInfo method = typeof(Enumerable).GetMethods().Where(m => m.Name == "Any" && m.GetParameters().Length == 2).Single().MakeGenericMethod(typeof(Participant));

MemberExpression propertyOuter = Expression.Property(c, "Participant");

var anyExpression = Expression.Call(method, propertyOuter, innerFunction);

2 个答案:

答案 0 :(得分:0)

也许这对你有用。

var queryResults = _db.Persons
   .Where( p => p.FirstName == "test3")
   .SelectMany(p => p.Participant.Projects)
   .Include("Participants.Person"); 

修改:或者如果有多个参与者

var queryResults = _db.Persons
   .Where( p => p.FirstName == "test3")
   .SelectMany(p => p.Participants.SelectMany(par => par.Projects))
   .Include("Participants.Person"); 

答案 1 :(得分:0)

我得到了解决方案,它的工作。

Lambda表达

var queryResults = _db.Projects
       .Include("Participants.Person")
       .Where(Project => Project.Participants.Any(Participant => Participant.Person.FirstName == "test3"));

构建动态lambda表达式的源代码

 ParameterExpression c = Expression.Parameter(typeof(T), entityType.Name);
 ParameterExpression tpe = Expression.Parameter(typeof(Participant), "Participant");
 Expression left1 = Expression.Property(tpe, typeof(Participant).GetProperty("Person"));
 Expression left2 = Expression.Property(left1, typeof(Person).GetProperty("FirstName"));
 Expression right1 = Expression.Constant(filter.FieldValue);
 Expression InnerLambda = Expression.Equal(left2, right1);
 Expression<Func<Participant, bool>> innerFunction = Expression.Lambda<Func<Participant, bool>>(InnerLambda, tpe);

 MethodInfo method = typeof(Enumerable).GetMethods().Where(m => m.Name == "Any" && m.GetParameters().Length == 2).Single().MakeGenericMethod(typeof(Participant));

 var outer = Expression.Property(c, typeof(Project).GetProperty("Participants"));

 var anyExpression = Expression.Call(method, outer, innerFunction);

这有很多帮助。 Building a dynamic expression tree to filter on a collection property