过滤数据时Linq查询异常

时间:2014-12-29 07:26:22

标签: c# linq linq-to-sql linq-to-entities extension-methods

我想通过traineeid过滤注册和未注册的课程。在这里,db Trainee(ID,TraineeName),Course(ID,CourseName),TraineeCourseEnrollment(TraineeID,CourseID,ENrolledDate)中有3个表。我可以简单地查询已注册的课程,但很难查询未注册的课程。这是我的代码......

    public IEnumerable<CourseDTO> GetCourse(string traineeid, bool isenrolled)
    {


        List<Course> enrolled=new List<Course>();
        List<CourseDTO> course_enrolled_dtos= new List<CourseDTO>();
        List<CourseDTO> course_unenrolled_dtos = new List<CourseDTO>();

        IEnumerable<TraineeCourseEnrollment> enrolled_courses = db.Trainees.Find(traineeid).TraineeCourseEnrollments.ToList();
        foreach (TraineeCourseEnrollment enroll in enrolled_courses)
        {
            course_enrolled_dtos.Add(new CourseDTO() { CourseName = enroll.Course.CourseName, ID = enroll.Course.ID });
            enrolled.Add(new Course() { CourseName = enroll.Course.CourseName, ID = enroll.Course.ID });
        }

        if(isenrolled)
        {
            return course_enrolled_dtos;
        }
        else
        {
            IEnumerable<Course> unenrolled=db.Courses.Except(enrolled); 
            foreach (Course unenroll in unenrolled)//Exception
            {
                course_unenrolled_dtos.Add(new CourseDTO() { CourseName = unenroll.CourseName, ID = unenroll.ID });
            }
            return course_enrolled_dtos;
        }




    }

此代码给出异常

  

无法创建类型&#39; DAL_EF1.Course&#39;的常量值。在此上下文中仅支持原始类型或枚举类型。

这里有使用Linq扩展方法查询此数据的最佳方法。

2 个答案:

答案 0 :(得分:1)

我认为您的代码中存在问题:

IEnumerable<Course> unenrolled=db.Courses.Except(enrolled);

您正尝试通过该对象过滤数据。相反,你可以尝试这样的事情:

IEnumerable<Course> unenrolled=db.Courses.Where(c => !enroller.Contains(c.ID)).ToList();

答案 1 :(得分:0)

该错误表明实体框架仅允许过滤器中的基元类型。

试试这个。

替换,

    IEnumerable<Course> unenrolled=db.Courses.Except(enrolled); 

用,

       var enrolledID = enrolled.Select(e => e.CourseID).ToList();
       IEnumerable<Course> unenrolled=db.Courses.Where(c => !enrolledID.Contains(c.CourseID));