Entity Framework查询中如何连接字符串?

18
如何在Entity Framework 4中连接字符串?我有来自一个列的数据,我想将其保存为以逗号分隔的字符串,例如"value1, value2, value3" EF4 中是否有相应的方法或运算符? 例如:假设我有两个列和,它们的值如下所示:
  • Apples
  • Bananas
  • Strawberries
如果我这样做:
var dataSource = this.context
    .Farms
    .Select(f => new
        {
            f.Id, 
            Fruits = string.Join(", ", f.Fruits)
        });
我会得到以下错误:
LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
这个问题有解决方案吗?
2个回答

17

在投影之前,您必须执行查询。否则,EF会尝试将Join方法转换为SQL(显然会失败)。

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

2
问题是我希望 dataSource 是 IQueryable<T>,以将其绑定到网格,那么它将执行服务器分页本身。 - Ahmed Magdy
3
那就先分页再拼接。 - Craig Stuntz

1

如果有人需要,我会提供我的答案,参考@Yakimych的回答:

using (myDBEntities db = new myDBEntities())
            {
                var results = db.Table
                    .ToList()
                    .Where(x => x.LastName.StartsWith("K"))
                    .Select(
                    x => new
                    {
                        x.ID,
                        Name = x.LastName + ", " + x.FirstName
                    }
                    );

                lstCoaches.DataValueField = "ID";
                lstCoaches.DataTextField = "Name";
                lstCoaches.DataSource = results;
                lstCoaches.DataBind();
                ListItem item = new ListItem
                {
                    Value = "0",
                    Text = "-- Make a Selection --"
                };
                lstCoaches.Items.Insert(0,item);
                lstCoaches.SelectedIndex = 0;
            }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接