简体   繁体   中英

C# Entity Framework: Subtracting entities

I have 3 entities Teacher , Subject , SchoolYear and SchoolYearSubject . SchoolYear, Teacher and Subject have many SchoolYearSubject. SchoolYear should have many Subjects each with its one Teacher, so I use SchoolYearSubject to store this relationship.

class Teacher { ICollection<SchoolYearSubject> }
class Subject { ICollection<SchoolYearSubject> }
class SchoolYear { ICollection<SchoolYearSubject> }
class SchoolYearSubject { Teacher, Subject, SchoolYear }

For example: We have SchoolYear 2010, 3 subjects sA, sB and sC and 3 teachers tA, tB, tC.

SchoolYear 2010 has 2 subjects sA and sC with teachers tA and respectively tC, so it has 2 SchoolYearSubject entities, one with a reference to the sA subject and tA teacher, and one with the sC subject and tC teacher.

How can I get for each SchoolYear the Subjects that aren't already in that SchoolYear, without storing local information about the Subjects present already in the SchoolYear ?

I tried using

SchoolYear SchoolYear = (SchoolYear 2010);
Db.Subjects.Except(SchoolYear.SchoolYearSubjects.Select(schoolYearSubject => schoolYearSubject.Subject)).ToList()

but it does not work, resulting in an NotSupportedException "Unable to create a constant value of type 'SchoolYearSubject'. Only primitive types ('such as Int32, String, and Guid') are supported in this context." as expected.

I presume your Subject class has an ID? You can build an array of the ID's you don't want to load and use Contains :

var subjectIDsInSchoolYear = SchoolYear.Subjects.Select(s => s.ID).ToArray();

var query = from s in Db.Subjects
            where !subjectIDsInSchoolYear.Contains(s.ID)
            select s;

var result = query.ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM