0

以下代码正在运行

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);
4

2 回答 2

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"); 
于 2012-11-02T13:51:36.410 回答
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);

这帮助很大。构建动态表达式树以过滤集合属性

于 2012-11-05T12:54:08.197 回答