【问题标题】:Linq Join with Dynamic ExpressionLinq Join 与动态表达式
【发布时间】:2013-11-15 23:37:51
【问题描述】:

我正在尝试在 linq 中进行动态连接。这意味着我只在运行时知道连接将发生在哪个字段上。

我做了以下事情:

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>>

如何让它动态创建使用我的字段的正确表达式(即typeof(E).GetMember(Field).First()) 行中的属性“Field”?

【问题讨论】:

    标签: c# linq lambda linq-expressions


    【解决方案1】:

    使用Expression.Lambda<TDelegate>,这样你就得到了这条线

    // obj => obj.Field
    var lambda = Expression.Lambda<Func<E, int>>(entityAccess, itemParam);
    

    更新

    根据您的评论,表达式失败的原因是您使用了两个不同的参数。你定义了itemParam,但随后不要在Expression.MakeMemberAccess中使用它

    请尝试以下方法:

    // obj
    var itemParam = Expression.Parameter(typeof(E), "obj");
    
    // obj.Field
    var entityAccess = Expression.MakeMemberAccess(itemParam, typeof(E).GetMember(Field).First());
    

    【讨论】:

    • 编译但我得到:参数'obj'未绑定在指定的LINQ to Entities查询表达式中。谢谢!
    • 看看我的更新,你需要使用来自Expression.Parameter的同一个实例
    • 没问题,我发现在评论中编写等效的 C# 有助于跟踪正在发生的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 2011-11-22
    • 1970-01-01
    • 2017-05-23
    • 2014-11-25
    • 1970-01-01
    相关资源
    最近更新 更多