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

标签 c# linq

我有这样一个类:

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

关于c# - 将select查询映射到一个对象会在linq中出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22062143/

相关文章:

c# - 从 C# 桌面应用程序向远程服务器上的 MySql 数据库添加数据

c# - 无法安装或运行应用程序 - System.Windows.Interactivity 版本 4.0.0.0

.net - 包含在 linq to entity 中的条件

linq - LINQ 中的标准差

c# - 使用 COUNT 和 GROUP 的 LINQ Case 语句

c# - User32.dll ToUnicodeEx函数的使用

c# - 当使用 JSON 中的重复键反序列化字典时,如何强制抛出异常?

c# - 根据节点名称拆分大型 JSON 的通用代码

c# - LINQ:如何返回所有父元素的所有子元素

c# - 我如何将 List<Dictionary<string, object>> 转换为 List<[具有动态属性的新类]>