2012-03-10 36 views
6

我有一個用戶列表,每個用戶都有問題列表。在我的模型列表中,問題應通過逗號串入。我嘗試:LINQ,無法加入字符串

public List<ITW2012Mobile.ViewModels.AdminSurveyReportModel> SurveyReportList() 
{ 
    var q = from i in _dbContext.Users 
      where i.UserId != null 
      select new ITW2012Mobile.ViewModels.AdminSurveyReportModel() 
      { 
       FirstName = i.FirstName, 
       LastName = i.LastName, 
       Question4 = String.Join(", " , (from a in _dbContext.MultipleQuestions where a.MultipleQuestionType.KEY == MultipleQuestionKeys.BENEFITS select a.Question).ToArray()) 
      }; 
    return q.ToList(); 
} 

public class AdminSurveyReportModel 
{ 
    public string FirstName { get; set; } 
    public string LastName { get; set; } 
    public string Question4 { get; set; } 
} 
當然

,我得到錯誤:

LINQ to Entities does not recognize the method 'System.String Join(System.String, System.String[])' method, and this method cannot be translated into a store expression.

如何正確地得到它?

+2

而不是'linq',剛剛返回集合並做檢索 – 2012-03-10 14:07:08

回答

14

我建議在當地做string.Join操作,而不是使用AsEnumerable

var q = from i in _dbContext.Users 
     where i.UserId != null 
     select new 
     { 
      FirstName = i.FirstName, 
      LastName = i.LastName, 
      Question4Parts = _dbContext.MultipleQuestions 
             .Where(a => a.MultipleQuestionType.KEY == 
                MultipleQuestionKeys.BENEFITS) 
             .Select(a => a.Question) 
     }; 

return q.AsEnumerable() 
     .Select(x => new ITW2012Mobile.ViewModels.AdminSurveyReportModel 
        { 
         FirstName = x.FirstName, 
         LastName = x.LastName, 
         Question4 = string.Join(", ", x.Question4Parts) 
        }) 
     .ToList(); 
+0

後加入問題4的類型爲字符串,用你的選擇已經sentense型IQuerable ... – John 2012-03-10 14:17:35

+1

加盟@約翰:那很好 - 因爲'q'我只爲匿名類型「T」創建'IQueryable '。我只把它轉換成第二部分的'AdminSurveyReportModel'。我會重命名該屬性以使其更清晰。 – 2012-03-10 14:23:10

+0

哦,失去了它。非常感謝你! – John 2012-03-10 14:32:21

-3

嘗試使用Aggregate方法。

Question4 = (from a in _dbContext.MultipleQuestions where a.MultipleQuestionType.KEY == MultipleQuestionKeys.BENEFITS select a.Question).ToArray().Aggregate((x,y) => x + "," + y) 

沒有測試

+0

不,它不起作用:LINQ to Entities不能識別方法System.String Aggregate [String](System.Collections.Generic.IEnumerable'1 [System.String],System.Func'3 [System.String, System.String,System.String])'方法,並且此方法不能轉換爲商店表達式。 – John 2012-03-10 14:15:26

0

不能包括的string.join()在初始投影,因爲LINQ轉換器不支持它。我可以爲它編寫一個自定義翻譯器嗎?