LINQ,无法创建 XXX 类型的常量值.此上下文中仅支持原始类型或枚举类型 [英] LINQ, Unable to create a constant value of type XXX. Only primitive types or enumeration types are supported in this context
本文介绍了LINQ,无法创建 XXX 类型的常量值.此上下文中仅支持原始类型或枚举类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用程序中,我有讲师,他们有可以教授的课程列表,当我删除课程时,我想删除与讲师的连接.代码如下:
In my application I have Lecturers and they have list of Courses they can teach and when I'm deleting a course I want to remove connection to lecturers. Here's the code:
public void RemoveCourse(int courseId)
{
using (var db = new AcademicTimetableDbContext())
{
var courseFromDb = db.Courses.Find(courseId);
var toRemove = db.Lecturers
.Where(l => l.Courses.Contains(courseFromDb)).ToList();
foreach (var lecturer in toRemove)
{
lecturer.Courses.Remove(courseFromDb);
}
db.SaveChanges();
}
}
但它不起作用.我得到
NotSupportedException:无法创建 Course
类型的常量值.此上下文中仅支持原始类型或枚举类型.
NotSupportedException: Unable to create a constant value of type
Course
. Only primitive types or enumeration types are supported in this context.
我做错了什么?
推荐答案
您不能将 Contains
与非原始值一起使用.做
You can't use Contains
with non-primitive values. Do
Where(l => l.Courses.Select(c => c.CourseId).Contains(courseId)
(或您使用的 Id 字段).
(or the Id field you use).
这篇关于LINQ,无法创建 XXX 类型的常量值.此上下文中仅支持原始类型或枚举类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文