我的控制器隐式创建var x:
var x = from sem in db.Semesters
join ss in db.StudentSemesters on sem.Id equals ss.SemesterId into sss
from ss in sss.Where(ss => ss.StudentId == id).DefaultIfEmpty()
select new
{
SemsterName = sem.Name,
SemesterId = sem.Id,
IsAssociated = ss.StudentId != null
};
我希望将此数据作为一个名为StudentSemesterAssociation的强类型businessmodel(成员:字符串SemesterName,int SemesterId,bool StudentIsAssociated)传递给视图,而不是将其传递给视图。
如何调整上面的var生成查询以返回StudentSemesterAssociation?
ViewModel.StudentSemesterAssociation = ???
问候,盖伊
答案 0 :(得分:3)
在查询的new
部分select
关键字后添加您的班级名称:
var x = from sem in db.Semesters
join ss in db.StudentSemesters on sem.Id equals ss.SemesterId into sss
from ss in sss.Where(ss => ss.StudentId == id).DefaultIfEmpty()
select new StudentSemesterAssociation
{
SemsterName = sem.Name,
SemesterId = sem.Id,
IsAssociated = ss.StudentId != null
};
这将使x
类型为IEnumerable<StudentSemesterAssociation>
,而不是匿名类型的集合。
顺便说一下。 var
不会使您的变量弱输入。您应该阅读var
keyword和隐式输入的局部变量。