Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

sql - How do I concatenate strings in Entity Framework Query?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)
                      });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...