Skip to main content
 首页 » 编程设计

c#之将select查询映射到一个对象会在linq中出错

2024年02月13日16lyhabc

我有这样一个类:

public class studentpres 
{ 
  public string stuname { set; get; } 
  public  string stlastaname { set; get; } 
  public string stunumber { set; get; } 
  public string stumajor { set; get; } 
  public string stufiled { set; get; } 
  public string stuaverage { set; get; } 
  public string stumobile { set; get; } 
  public string stuemail { set; get; } 
  public string stuprofSupervisor { set; get; } 
  public string prifsuperEmail { set; get; } 
} 

我这样查询:

public studentpres Get_Student_List(string stuNumber) 
{ 
    studentpres temp = 
        from i in dbconnect.tblUsers 
        join d in dbconnect.tblNovitiates 
            on i.tblStudent.studentNumber equals d.studentNumber 
        select new PresentClass.studentpres() 
        { 
            prifsuperEmail = d.profSupervisorUSername, 
            stlastaname = i.family, 
            stuaverage = i.tblStudent.average, 
            stuemail = i.email, 
            stufiled = i.tblStudent.field, 
            stumajor = i.tblStudent.major, 
            stumobile = i.mobile, 
            stuname = i.name, 
            stunumber = i.tblStudent.studentNumber, 
            stuprofSupervisor = Return_Name_By_userName(d.profSupervisorUSername) 
        }; 
} 

但是我得到了这个错误:

Cannot implicitly convert type
'System.Linq.IQueryable<Novitiate.AdminPortal.PresentationClass.PresentClass.studentpres>' to 'Novitiate.AdminPortal.PresentationClass.PresentClass.studentpres'. An explicit conversion exists (are you missing a cast?)

我还在查询的末尾添加了一个 Tolist() 但它再次不起作用; 谢谢

请您参考如下方法:

您的查询返回 IQueryable<studentpres> ,你应该只选择一条记录,使用:Single , First或其他方法:

  1. 单例
  2. 单一或默认
  3. 首先
  4. FirstOrDefault