我需要为针对 OData Web 服务的动态搜索创建一个动态 linq 表达式。基本搜索正在工作,但有嵌套表不起作用。
格式为 webservice/Books('id')/Author
我可以让它工作
var authors = from p in webservice.Books.Expand("Author")
where p.Title.Equals("Watership Down") && p.Author.FirstName.Equals("Richard")
select p;
我已将其更改为以下内容:
var authors = webservice.Books.Expand("Author").Where(condition);
我构造条件如下:
ParameterExpression pe = Expression.Parameter(typeof(webservice.Books), "p");
Expression left = Expression.Property(pe, "Title");
Expression right = Expression.Constant("Watership Down");
Expression predicateBody = Expression.Equal(left, right);
Expression<Func<webservice.Books, bool>> condition = Expression.Lambda
<Func<webservice.Books, bool>>(predicateBody, new ParameterExpression[] { pe });
哪个有效。
所以如果我尝试
ParameterExpression pe = Expression.Parameter(typeof(webservice.Books), "p");
Expression left = Expression.Property(pe, "Title");
Expression right = Expression.Constant("Watership Down");
Expression e = Expression.Equal(left, right);
left = Expression.Property(pe, "Author.FirstName");
right = Expression.Constant("Richard");
Expression e2 = Expression.Equal(left, right);
Expression predicateBody = Expression.And(e, e2);
Expression<Func<webservice.Books, bool>> condition = Expression.Lambda
<Func<webservice.Books, bool>>(predicateBody, new ParameterExpression[] { pe });
但它不起作用。它不将 Author.FirstName 识别为属性。我认为这是因为我将 pe 声明为 Books 类型,所以它看不到嵌套的 Author 但我不知道如何声明它,所以它会看到嵌套的数据。
确切的错误消息是没有为类型“webServices.Books”定义实例属性“Author.FirstName”
有谁知道如何做到这一点?甚至可能吗?感谢任何人对此提供的任何帮助。
为了解决这个错误,我必须做的是改变 left = Expression.Property(pe, "Author.FirstName"); to Expression property = Expression.Property(pe, "Author"); left = Expression.Property(property, "FirstName");
现在它起作用了!
谢谢!