Linq结合动态表达 [英] Linq Join with Dynamic Expression
问题描述
我正在尝试在linq中进行动态连接.这意味着我仅在运行时知道联接将在哪个字段上发生.
I'm attempting to do a dynamic join in linq. Meaning that I only know at runtime what field the join will occur on.
我已完成以下操作:
var itemParam = Expression.Parameter(typeof(E), "obj");
var entityAccess = Expression.MakeMemberAccess(Expression.Parameter(typeof(E), "obj"), typeof(E).GetMember(Field).First());
var lambda = Expression.Lambda(entityAccess, itemParam);
var q = dbSet.Join(context.Acl, lambda, acl => acl.ObjectID, (entity, acl) => new { Entity = entity, ACL = acl });
尽管这会在编译时抛出,即使lambda似乎是正确的语法,告诉我它无法从LambdaExpression转换为Expression<System.Func<E, int>>
.
However this throws at compile time, even though lambda appears to be the right syntax telling me that it cannot convert from LambdaExpression to Expression<System.Func<E, int>>
.
如何获取它以动态使用我的字段(即上面typeof(E).GetMember(Field).First())
行中的字段"属性)创建正确的表达式?
How do I get it to create the right expression dynamically that uses my field (i.e. property "Field" above in the typeof(E).GetMember(Field).First())
line?
推荐答案
Use Expression.Lambda<TDelegate>
, so that you end up with the line
// obj => obj.Field
var lambda = Expression.Lambda<Func<E, int>>(entityAccess, itemParam);
更新
根据您的评论,表达式失败的原因是因为您使用的是两个不同的参数.您定义了itemParam
,但是不要在Expression.MakeMemberAccess
As per your comment, the reason the expression fails is because you are using two different parameters. You define itemParam
, but then do not use it in Expression.MakeMemberAccess
请尝试以下操作:
// obj
var itemParam = Expression.Parameter(typeof(E), "obj");
// obj.Field
var entityAccess = Expression.MakeMemberAccess(itemParam, typeof(E).GetMember(Field).First());
这篇关于Linq结合动态表达的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!