我有一个这样的课程:
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)
};
}
但我收到了这个错误:
无法隐式转换类型
'System.Linq.IQueryable<Novitiate.AdminPortal.PresentationClass.PresentClass.studentpres>'
至'Novitiate.AdminPortal.PresentationClass.PresentClass.studentpres'
。 存在显式转换(您是否错过了演员?)
我还在查询结尾添加了 Tolist(),但它没有再次运行; 感谢
答案 0 :(得分:3)
您的查询返回IQueryable<studentpres>
,您应该只选择一条记录,使用:Single
,First
或其他方法:
答案 1 :(得分:1)
您的查询返回IQueryable<studentpres>
结果,但您尝试将其分配给studentpres
类型的变量。如果您期望得到很多结果,那么将方法的返回类型(从方法名称我假设您需要这样做)更改为IQueryable<studentpres>
或IEnumerable<studentpres>
:
public IQueryable<studentpres> Get_Student_List(string stuNumber)
{
return 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,
// ...
};
}
注意 - IQueryable<studentpress>
将返回查询而不是查询执行的结果。如果要获取查询结果,则应执行它(即将查询结果保存到列表中):
public IList<studentpres> Get_Student_List(string stuNumber)
{
var query = 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)
};
return query.ToList(); // executes query
}
如果您想获得单个结果,请在查询时拨打FistOrDefault()
或SingleOrDefault()
:
public studentpres Get_Student_List(string stuNumber)
{
var query = 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,
// ...
};
return query.FirstOrDefault();
}