如何在实体框架查询中连接字符串?

Ahm*_*gdy 14 sql entity-framework aggregate string-concatenation entity-framework-4

如何在实体框架4中连接字符串我有一个列中的数据,我想将字符串保存为逗号分隔的字符串,如"value1,value2,value3"是否有方法或操作员在EF4中执行此操作?示例:假设我有两列FruitFarms具有以下值:

  • 苹果
  • 香蕉
  • 草莓

如果我喜欢这个

var dataSource = this.context
    .Farms
    .Select(f => new
        {
            f.Id, 
            Fruits = string.Join(", ", f.Fruits)
        });

当然我会得到这个错误

LINQ to Entities无法识别方法'System.String Join(System.String,System.Collections.Generic.IEnumerable`1 [System.String])'方法,并且此方法无法转换为商店表达式.

这有什么解决方案吗?

Yak*_*ych 13

您必须在投影前执行查询.否则EF会尝试将Join方法转换为SQL(并且明显失败).

var results = this.context
                  .Farms
                  .ToList()
                  .Select(f => new
                      {
                          f.Id, 
                          Fruits = string.Join(", ", f.Fruits)
                      });
Run Code Online (Sandbox Code Playgroud)

  • 问题是我希望 dataSource 是 IQueryable<T> 将它绑定到网格然后它会这样服务器分页本身。 (2认同)
  • 然后在连接之前进行分页. (2认同)