2012-03-10 32 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转换器不支持它。我可以为它编写一个自定义翻译器吗?