实体框架,无法创建类型为';XX';.在此上下文中仅支持基元类型或枚举类型
本文关键字:类型 上下文 支持 枚举 创建 框架 XX 实体 | 更新日期: 2023-09-27 18:00:27
我有一个方法,它返回如下定义的视图模型:
if (studentId != null)
{
var eduRec = (_context.EducationalRecords.Where(x => x.StudentId == studentId)).ToList();
var guarnator = (_context.NextOfKinGuarantors.Where(x => x.StudentId == studentId)).ToList();
model = (from stud in _context.Students
join lga in _context.LocalGovts
on stud.LocalGovtId equals lga.LocalGovtId
join st in _context.States
on lga.StateId equals st.StateId
join acada in _context.AcademicRecords
on stud.StudentId equals acada.StudentId
join dept in _context.Departments
on acada.DepartmentId equals dept.DepartmentId
join faculty in _context.Falculties
on dept.FalcultyId equals faculty.FalcultyId
join prg in _context.Programmes
on acada.ProgrammeId equals prg.ProgrammeId
join lvl in _context.Levels
on acada.LevelId equals lvl.LevelId
where acada.IsCurrentRecord == true && stud.StudentId == studentId
select new StudentProfileViewModel()
{
ContactAddress = stud.ContactAddress,
Department = dept.Name,
Disability = stud.Disability,
Othernames = stud.Othernames,
FirstName = stud.FirstName,
Surname = stud.Surname,
Programme = prg.Name,
RegistrationNumber = stud.RegistrationNumber,
Dob = stud.Dob,
EducationalRecords = eduRec,
Email = stud.Email,
Faculty = faculty.Name,
Gender = stud.Gender,
HomeAddress = stud.HomeAddress,
Level = lvl.Name,
LocalGoverment = lga.Name,
MaritalStatus = stud.MaritalStatus,
Phone = stud.Phone,
Religion = stud.Religion,
StateName = st.Name,
NextOfKinGuarantors = guarnator
}).FirstOrDefault();
}
当我运行应用程序时,我收到了以下错误消息:
无法创建类型为"Portal.Models.EducationalRecord"的常量值。此上下文仅支持基元类型或枚举类型
EducationalRecords
的定义是一个列表。
您的LINQ语句必须可翻译为有效的SQL查询,因此您必须小心调用的内容。例如,如果您尝试调用您在C#中编写的某个随机方法,则可能无法转换为有效的SQL,因此会出现错误。
在您的案例中,它抱怨试图使用单独的LINQ语句填充EducationalRecords
,显然它无法将其转换为单个SQL语句。
从LINQ语句中删除此行:
EducationalRecords = eduRec,
在填充model
:之后,单独获取EducationalRecords
if (model != null)
model.EducationalRecords =
_context.EducationalRecords.Where(x => x.StudentId == studentId)).ToList();
Grant已经在您发布的代码中处理了这个问题,但有一个更好的解决方案可以解决整个问题。使用具有急切加载的导航属性。这将使您免于进行三次单独的数据库往返数据库以收集这些信息。
以下是MSDN关于如何在代码优先、模型优先和数据库优先中创建导航属性的信息。