EpiServer DynamicDataStore LINQ语句中的SQL语法不正确

我正在写一个查询以从DynamicDataStoreEpiserver中检索一些数据当我运行代码时,出现以下错误:

System.Data.SqlClient.SqlException:'>'附近的语法不正确。

这是相关的查询:

BlogContentStore store = new BlogContentStore();
IQueryable<UwlBlogPost> posts = store.Posts.Where(p => Blog == p.BlogId && p.ReadyToPost && p.PostOn <= DateTime.Now);
if (taggedPeople.Count() > 0 || taggedDepartments.Count() > 0 || taggedDepartments.Count() > 0)
{
    posts = posts.Where(p => p.PeopleTags.Intersect(taggedPeople).Count() > 0
        || p.DepartmentTags.Intersect(taggedDepartments).Count() > 0
        || p.KeywordTags.Intersect(taggedKeywords).Count() > 0);
}
posts = posts.OrderByDescending(p => p.PostOn).Take(DisplayCount);

在我看来,所有语法都可以,并且可以编译。

我设法解决了这个问题。查看SQL Server日志,我发现Intersect语句没有变成SQL,所以我决定动态创建查询表达式来解决它:

if (taggedPeople.Count > 0 || taggedDepartments.Count > 0 || taggedKeywords.Count > 0)
{
    ParameterExpression paramExpr = Expression.Parameter(typeof(UwlBlogPost), "p");
    Expression peopleTagsExpr = Expression.Property(paramExpr, "PeopleTags");
    Expression deptTagsExpr = Expression.Property(paramExpr, "DepartmentTags");
    Expression keywordTagsExpr = Expression.Property(paramExpr, "KeywordTags");

    Expression filterExpr = null;
    if(taggedPeople.Count > 0)
    {
        filterExpr = FilterLambda<string>(taggedPeople, peopleTagsExpr, paramExpr);
    }
    if(taggedDepartments.Count > 0)
    {
        Expression filter = FilterLambda<int>(taggedDepartments, deptTagsExpr, paramExpr);
        filterExpr = (filterExpr == null) ? filter : MatchAll ? Expression.And(filterExpr, filter) : Expression.Or(filterExpr, filter);
    }
    if(taggedKeywords.Count > 0)
    {
        Expression filter = FilterLambda<int>(taggedKeywords, keywordTagsExpr, paramExpr);
        filterExpr = (filterExpr == null) ? filter : MatchAll ? Expression.And(filterExpr, filter) : Expression.Or(filterExpr, filter);
    }

    posts = posts.Where(Expression.Lambda<Func<UwlBlogPost, bool>>(filterExpr, new[] { paramExpr }));
}


private Expression FilterLambda<T>(List<T> tags, Expression field, ParameterExpression paramExpr)
{
    Expression firstTag = Expression.Constant(tags.First());
    Expression root = Expression.Call(field, tags.GetType().GetMethod("Contains"), firstTag);
    if (tags.Count > 1)
    {
        foreach (T tag in tags.Skip(1))
        {
            Expression singleTag = Expression.Constant(tag);
            Expression cond = Expression.Call(field, tags.GetType().GetMethod("Contains"), singleTag);
            root = MatchAll ?  Expression.And(root, cond) : Expression.Or(root, cond);
        }
    }
    return root;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章