如何在Entity Framework Query中连接字符串? [英] How do I concatenate strings in Entity Framework Query?

查看:171
本文介绍了如何在Entity Framework Query中连接字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何连接Entity Framework中的字符串4我有一个列的数据,我想以字符串形式保存一个逗号分隔的字符串,如value1,value2,value3
是否有方法或操作符在EF4中做这个吗?
示例:让我们说,我有两列 Fruit Farms 具有以下值:



  • 苹果

  • 香蕉

  • 草莓



如果我这样做

 
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])'方法,并且此方法不能转换为存储表达式。

有没有解决方法?

解决方案

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

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


How do I concatenate strings in Entity Framework 4 I have a data from a column and I want to save as a string a comma separated string like "value1, value2, value3" Is there a method or an operator do do this in EF4? Example: lets say that I have two columns Fruit and Farms with the following values:

  • Apples
  • Bananas
  • Strawberries

If I do like this

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

Sure I will get this error

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.

Is there any solution to this?

解决方案

You have to execute the query before projecting. Otherwise EF tries to translate the Join method into SQL (and obviously fails).

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

这篇关于如何在Entity Framework Query中连接字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆