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

时间:2010-11-04 10:20:31

标签: sql entity-framework entity-framework-4 aggregate string-concatenation

如何在Entity Framework 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])'方法,并且此方法无法转换为商店表达式。

有没有解决方案?

2 个答案:

答案 0 :(得分:13)

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

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

答案 1 :(得分: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;
            }