【问题标题】:Expression Tree throws error表达式树引发错误
【发布时间】:2014-06-12 12:27:20
【问题描述】:

在我的 VS LIGHTSWITCH 2013 门户应用程序中,我允许用户创建链接到其他内部应用程序的图块。当创建新图块时,将创建一个名为“TileTitle +“用户”的角色。这样我可以根据用户角色显示和隐藏图块。但是,当尝试在查询过滤器方法中过滤平铺实体时,我收到一些关于无法使用 IsInRole 方法的错误。

经过一番挖掘,我决定尝试一下表达式树,这就是我想出的:

partial void TileLinks_Filter(ref Expression<Func<TileLink, bool>> filter)
{
    ParameterExpression p = Expression.Parameter(typeof(TileLink), "e");
    MemberExpression ti = Expression.Property(p, "Title");
    MethodInfo m2 = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) });


    Type t = this.Application.User.GetType();
    MethodInfo m = t.GetMethod("IsInRole");

    Expression filterExpression = Expression.IsTrue(Expression.Call(Expression.Call(m2, ti, Expression.Constant(" User")), m));

    filter = Expression.Lambda<Func<TileLink, bool>>(filterExpression, p); 

    // e => this.Application.User.IsInRole(e.Title + " User"); 
    // this is what I would like to do
 }

但是这不起作用,我留下了这个非常奇怪的错误消息。

Method 'Boolean IsInRole(System.String)' declared on type 'System.Security.Claims.ClaimsPrincipal' cannot be called with instance of type 'System.String'

请帮我根据动态生成的角色过滤我的数据!

【问题讨论】:

    标签: .net expression-trees visual-studio-lightswitch claims-based-identity


    【解决方案1】:

    在对Expression.Call 的外部调用中,你的论点被颠倒了。如果你把你的代码弄破了一点,你会得到这样的结果:

    var titlePlusUser = Expression.Call(m2, ti, Expression.Constant(" User"));
    var isInRole = Expression.Call(titlePlusUser, m); // <<-- !!!
    Expression filterExpression = Expression.IsTrue(isInRole);
    

    这是指示它使用e.Title + "User" 作为对象实例来调用IsInRole

    相反,您需要生成另一个知道如何获取this.Application.User 的表达式,并将该表达式作为第一个参数传入。

    var isInRole = Expression.Call(applicationUser, m, titlePlusUser);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多