14

我如何连接实体框架中的字符串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加入(System.String,System.Collections.Generic.IEnumerable`1 [System.String])''方法,并且此方法无法转换为存储表达。

有没有解决方法?

回答

13

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

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

的问题是我想要的数据源是IQueryable的将其绑定到网格,然后它会因此服务器本身分页。 – 2010-11-04 10:36:52

+2

然后在连接之前进行分页。 – 2010-11-04 14:41:56

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; 
      } 
相关问题