表达式树抛出错误

时间:2014-06-12 12:27:20

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

在我的VS LIGHTSWITCH 2013门户网站应用程序中,我允许用户创建链接到其他内部应用程序的切片。当新的磁贴创建一个名为' TileTitle +"的角色时用户"'被建造。这样我就可以根据用户角色显示和隐藏切片。但是,当尝试在查询过滤器方法中过滤tile实体时,我得到一些关于无法使用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'

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

1 个答案:

答案 0 :(得分:0)

你在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);
相关问题