Linq Query Return Error

linq

33 观看

2回复

171 作者的声誉

I cannot figure out why my return from a linq query always is not correct.

  [HttpGet]
    public List<Programs> GetPrograms()
    {
        using (var context = new ProgramsDataContext1())
        {

             var qry = (from a in context.Programs 

                      join b in context.courselist on a.Prog_id equals(b.prog_id)
                      where a.Prog_id ==b.prog_id 
                      orderby a.Programname
                      select new 
                      { Prog_id =a.Prog_id,Programname=a.Programname, programlevel=a.programlevel, planname=a.planname, catalogNo=b.catalogNO, coursetitle=b.coursetitle, subject=b.subject
                      }
                      ).ToList();


            return qry ;
        }

    }

It always has a red underline on the qry. What is the problem here? Thanks.

作者: user788448 的来源 发布者: 2017 年 12 月 27 日

回应 2


1

12596 作者的声誉

Since you are doing the join already, you do not need the where clause. Also your return type is not the same, that's the error you are getting. You are right now returning a list of anonymous objects, not Programs

作者: AD.Net 发布者: 2017 年 12 月 27 日

0

188870 作者的声誉

Just define a class that lists just the properties you need from the two classes and instead of building an anonymous object create instances of this class.

public class ProgramsCourseDto
{
   public int Prog_id {get;set;}
   public string Programname {get;set;}
   public int programlevel {get;set;}
   public string planname {get;set;}
   public int catalogNo {get;set;}
   public string coursetitle {get;set;}
   public string subject {get;set;}
}

[HttpGet]
public List<ProgramsCourseDto> GetProgramsCourses()
{
    using (var context = new ProgramsDataContext1())
    {

         var qry = (from a in context.Programs 
                  join b in context.courselist on a.Prog_id equals(b.prog_id)
                  orderby a.Programname
                  select new ProgramsCourseDto
                  { 
                       Prog_id =a.Prog_id,
                       Programname=a.Programname, 
                       programlevel=a.programlevel, 
                       planname=a.planname, 
                       catalogNo=b.catalogNO, 
                       coursetitle=b.coursetitle, 
                       subject=b.subject
                  }).ToList();
        return qry ;
    }
}
作者: Steve 发布者: 2017 年 12 月 27 日
32x32