多个连接LINQ上的Join子句不正确

时间:2014-04-22 10:47:18

标签: c# linq join

我有这样的多连接查询:

public static List<Answer> GetDetailedAnswers(string Tag)
    {
        using (Database db = new Database())
        {

            List<Answer> answer = 
                         from quest in db.Question
                         join answ in db.Answer on quest.ID equals answ.QuestionID
                         join deal in db.Dealer on answ.DealerID equals deal.ID
                         join country in db.Country on deal.CountryID equals country.CountryID
                         where quest.ParentSection == Tag
                         select new 
                         { 
                                      ParentSection = quest.ParentSection, 
                                      Section = quest.Section, 
                                      Dealer = deal.Name, 
                                      OriginalAnswer = answ.Original,
                                      EngAnswer = answ.English,
                                      Region = country.Country
                         }.ToList();
            return answer;
        }
    }

我有一个像这样的内部课程:

public class Answer
    {
        public string ParentSection { get; set; }
        public string Section { get; set; }
        public string Dealer { get; set; }
        public string OriginalAnswer { get; set; }
        public string EngAnswer { get; set; }
        public string Region { get; set; }
    }

我在上一次加入时收到错误。它说“join子句中某个表达式的类型不正确。在'Join'调用中类型推断失败” 我错过了什么? THX

2 个答案:

答案 0 :(得分:0)

请检查

的数据类型

deal.CountryID和country.CountryID。这应该是相同的

答案 1 :(得分:0)

对于错误:&#34; AnonymousType#1不包含&#39; ToList&#39;的定义。并且没有扩展方法&#39; ToList&#39;&#34;,您可以执行以下操作。

  public static List<Answer> GetDetailedAnswers(string Tag)
{
    using (Database db = new Database())
    {

        List<Answer> answer = 
                     (from quest in db.Question
                     join answ in db.Answer on quest.ID equals answ.QuestionID
                     join deal in db.Dealer on answ.DealerID equals deal.ID
                     join country in db.Country on deal.CountryID equals country.CountryID
                     where quest.ParentSection == Tag
                     select new Answer
                     { 
                                  ParentSection = quest.ParentSection, 
                                  Section = quest.Section, 
                                  Dealer = deal.Name, 
                                  OriginalAnswer = answ.Original,
                                  EngAnswer = answ.English,
                                  Region = country.Country
                     }).ToList();
        return answer;
    }
}

您需要在圆括号内围绕查询,然后将.ToList()方法应用于它。