1

我在我的數據庫/實體框架模型中有一個多對多的結構。在實體框架中聚合多對多的一邊並綁定到gridview

CompanyNotice (MM) CompanyNoticesLocations (MM)位置

enter image description here

我試圖聚集一個CompanyNotice的位置,並返回一個逗號分隔LOCATIONNAME的位置。

if (!IsPostBack) 
      { 
       using (var context = new ALEntities()) 
       { 
        var query = from c in context.CompanyNotices.Include("Locations") 
           select new 
           { 
            c.CompanyNoticeHeading, 
            c.CompanyNoticeText, 
            c.IsHR, 
            locations = (from l in c.Locations select l.LocationName).Aggregate((current, next) => string.Format("{0}, {1}", current, next)) 

           }; 
        ASPxGridView1.DataSource = query; 
        ASPxGridView1.DataBind(); 
       } 
      } 

我收到以下錯誤,當我試着上面的代碼:

LINQ到實體無法識別方法「System.String 我曾嘗試使用下面的代碼來彙總LOCATIONNAME嘗試聚合[String](System.Collections.Generic.IEnumerable 1[System.String], System.Func 3 [System.String,System.String,System.String])'方法,並且 此方法不能被轉換爲商店表達式。

當我嘗試:

if (!IsPostBack) 
       { 
        using (var context = new ALEntities()) 
        { 
         var query = from c in context.CompanyNotices.Include("Locations") 
            select new 
            { 
             c.CompanyNoticeHeading, 
             c.CompanyNoticeText, 
             c.IsHR, 
             locations = (from l in c.Locations select l.LocationName) 

            }; 
         ASPxGridView1.DataSource = query; 
         ASPxGridView1.DataBind(); 
        } 
       } 

在GridView上的位置的列中的數據顯示爲:

System.Collections.Generic.List`1 [System.String]

有誰知道我該如何聚合一個CompanyNotice的LocationName?

在此先感謝。

回答

1

你會這樣......

using (var context = new ALEntities()) 
        { 
         var query = from c in context.CompanyNotices.Include("Locations") 
            select new 
            { 
             c.CompanyNoticeHeading, 
             c.CompanyNoticeText, 
             c.IsHR, 
             locations = (from l in c.Locations select l.LocationName) 

            }; 
var listed = query.ToList(); 
var commaListed = listed.Select (a=> new { a.CompanyNoticeHeading, a.CompanyNoticeText, 
commaLines = a.locations.Aggregate((s1, s2) => s1 + "," + s2)}); 

然後綁定commaListed您的DataGrid

+0

謝謝,這確實爲我工作,但是我決定使用一個存儲過程,而不是LINQ。 – Seany84