2017-06-25 7 views
0

linqステートメントで文字列連結を作成する必要があります。エンティティフレームワーク:データベースクエリの文字列concat

  • ID:1、タイトル:Test1を
  • イド:2、タイトル:Test2を

Section_User

    私は、次のデータを持っています
  • SectionId:1、UserId:1
  • セクションID:1、ユーザーID:2

ユーザー

  • イド:1、名前:ユーザー1
  • イド:2、名前:User2の

I次の結果が必要です。

セクションID:1、ユーザー:ユーザー1、ユーザー2

私は次のLINQ文を作成します。

var query2 = from section in this.context.Sections 
       from users in section.Users 
       group section by section2.Id into groupedSection 
       select new { 
        SectionId = groupedSection.Key, 
        Users = string.Join(",", users.Select (x => x.Name)) // compile error, but I don't know how I write the statement correctly 
       }; 

誰かが私に言うことができる、私はデータベース側の文字列の連結を作成する方法(ないメモリ内の) linq文を使用します。

ありがとうございます!コメントで@Alexeiのリンクに基づいて

+1

[この回答](https://stackoverflow.com/a/3428175/2780791)を確認してください。 – Alexei

+0

joinの代わりに 'string.format'を使うことができます。 – ISHIDA

+0

私はそれがEFによってサポートされているとは思わない。だから残念なことに答えは - あなたはできません。 –

答えて

1

それはエンティティのエラーに起因するLINQに動作しない、とあなたは、単に残して喜んでいる場合は、あなたの行は、しかし

var query2 = from section in this.context.Sections 
       from users in section.Users 
       group section by section2.Id into groupedSection 
       select new { 
        SectionId = groupedSection.Key, 
        Users = string.Join(",", (from u in users select s.Name).ToArray()) 
       }; 

のようになります。 UsersIEnumerable<string>として、あなたは、単に使用することができます。

var query2 = from section in this.context.Sections 
       from users in section.Users 
       group section by section2.Id into groupedSection 
       select new { 
        SectionId = groupedSection.Key, 
        Users = (from u in users select s.Name) 
       }; 

以降必要なとき、あなたは文字列を結合する、またはループを使用して名前を表示することができます。

+0

答えフォームAlexeiのリンクは私のためには機能しません。私は以下の答えを書いています:https://stackoverflow.com/a/44753791/2489386 –

+1

私はいくつかの時間を今検索しました、そして、あなたのconcat/joinオペレーションのために、 'ToList ) 'または' AsEnumerable() 'のように、純粋なMySQL文を記述して[Raw SQL queries](https://msdn.microsoft.com/en-us/library/)を使用して実行することが最も近いと思います。 jj592907(v = 117).aspx)。 –

関連する問題