开发者

LINQ-TO-sql expression for parent entity

I am trying to create Linq Expression that I can use to query child entity for parent properties(PATIENT entity in this case), using this method:

private IQueryable<LAB_ORDER> SelectFilter(string fieldName, string value)
{
   var param = Expression.Parameter(typeof(PATIENT), "item");
   var field = Expression.PropertyOrField(param, fieldName);

   var search = Expression.Constant(value, typeof(string));

   var body = Expression.Call(field, "Contains", null, search);

   Expression<Func<LAB_ORDER, bool>> lambda;

   if (String.IsNullOrEmpty(value))
   {
      lambda = x => true;
   }
   else
   {
      lambda = Expression.Lambda<Func<LAB_ORDER, bool>>(body, parm);

   }

   var linqFilter = from e in context.LAB_ORDERS select e;

   开发者_运维知识库return linqFilter.Where(lambda);
} 

Looks like it builds an expression correctly, but exception I am getting is this:

System.ArgumentException: ParameterExpression of type 'PATIENT' cannot be used for delegate parameter of type LAB_ORDER'.

While I can do linqFilter.Where( x => x.PATIENT.LAST_NAME == "Smith") without any problems, can't use expression above, which should translate to something similar to this. How would I fix the expression above to correct it? I am eagerly loading parent entity with a child so that's not a problem.

EDIT

From Anders reply it looks like I need to modify lambda expression to:

lambda = Expression.Lambda<Func<PATIENT, bool>>(body, parm);

Now when I try to use it, linqFilter.Where(lambda) gives me compile error "No suitable overload" which I understand why - linqFilter is "IQueryable<LAB_ORDER>", not "IQueryable<PATIENT>", so how should I do that? Just to sum things up, the only question remains - how to create Expression for parent properties?


In the following statement you say that you will build a function which takes a LAB_ORDER argument and returns a bool.

lambda = Expression.Lambda<Func<LAB_ORDER, bool>>(body, parm);

However the parm variable contains a PATIENT. You will have to rewrite the expression lambda to take an LAB_ORDER instead. If I understand your intentions you correctly the expression you are trying to express is

x => x.PATIENT.[fieldnName].Contains()

but the expression you've built is

x => x.[fieldName].Contains()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜