Linq2Db和string.join()

时间:2019-01-27 18:26:16

标签: c# linq2db

我在带有子查询的大型查询中使用Linq2db。 在其中一个位置,我想使用string.Join():

...
FullPath = string.Join(" -> ", GetPathQuery(db, c.Id).Select(pi => pi.Name))
...

但是我收到一个例外:

  

LinqException:'Join(“->”,value(RI.DAL.Categories.AdminCategoryPreviewDAL).GetPathQuery(value(RI.DAL.Categories.AdminCategoryPreviewDAL + <> c__DisplayClass4_0).db,c.Id).Select(pi => pi.Name))'无法转换为SQL。

我使用Postgre SQL,它具有concat_ws函数,对我来说是完美的。所以我尝试使用它:

[Sql.Expression("concat_ws({1}, {0})")]
public static string JoinAsString(this IQueryable<string> query, string separator)
{
    return string.Join(separator, query);
}

...
FullPath = GetPathQuery(db, c.Id).Select(pi => pi.Name).JoinAsString(" -> ")
...

但是我以同样的例外失败了。


GetPathQuery的完整源代码:

    private IQueryable<CategoryPathItemCte> GetPathQuery(IStoreDb db, Guid categoryId)
    {
        var categoryPathCte = db.GetCte<CategoryPathItemCte>(categoryHierarchy =>
        {
            return
                (
                    from c in db.Categories
                    where c.Id == categoryId
                    select new CategoryPathItemCte
                    {
                        CategoryId = c.Id,
                        ParentCategoryId = c.ParentId,
                        Name = c.Name,
                        SeoUrlName = c.SeoUrlName
                    }
                )
                .Concat
                (
                    from c in db.Categories
                    from eh in categoryHierarchy.InnerJoin(ch => ch.ParentCategoryId == c.Id)
                    select new CategoryPathItemCte
                    {
                        CategoryId = c.Id,
                        ParentCategoryId = c.ParentId,
                        Name = c.Name,
                        SeoUrlName = c.SeoUrlName
                    }
                );
        });

        return categoryPathCte;
    }

1 个答案:

答案 0 :(得分:1)

你能这样尝试吗?

FullPath = string.Join(" -> ", GetPathQuery(db, c.Id).Select(pi => pi.Name).ToList());

更友好的查询方式

GetPathQuery(db, c.Id).Select(pi => pi.Name)
   .Aggregate(string.Empty, (results, nextString) 
               => string.Format("{0} -> {1}", results, nextString));