14

Come concatenare le stringhe in Entity Framework 4 Ho un dato da una colonna e voglio salvare come stringa una stringa separata da virgola come "valore1, valore2, valore3" Esiste un metodo o un operatore che lo fa in EF4? Esempio: Diciamo che ho due colonne Fruit e Farms con i seguenti valori:Come concatenare le stringhe in Entity Framework Query?

  • Mele
  • Banane
  • Fragole

Se mi piace questo

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

Certo otterrò questo errore

LINQ to Entities non riconosce il metodo 'System.String Join (System.String, System.Collections.Generic.IEnumerable`1 [System.String])' metodo e questo metodo non può essere tradotto in un negozio espressione.

C'è qualche soluzione a questo?

risposta

13

È necessario eseguire la query prima di proiettare. In caso contrario, EF prova a tradurre il metodo Join in SQL (e ovviamente fallisce).

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

Il problema è che voglio il DataSource è IQueryable per associarlo alla rete allora sarà quindi il server di paging in sé . –

+2

Fare il paging prima della concatenazione, quindi. –

1

Ha preso risposta @Yakimych e pensiero fornirebbe mia, se qualcuno aveva bisogno:

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