c# - EF:使用桥接表删除对象
问题描述
我正在尝试跟踪出勤率和学生。为此,我正在使用桥接表。学生有一个 ICollection 的 PersonAttendances(bridgetable 和 bridgeclass),而出勤率也有一个 ICollection 的 personAttendances。
当一个人在某个日期(出勤属性)参加课程时,在出勤类中调用 addStudent 方法
public void AddPerson(Person person) {
PersonAttendance personAttendance = new PersonAttendance {
Person = person, Attendance = this,
AttendanceId = this.AttendanceId,
PersonId = person.PersonId
};
PersonAttendances.Add(personAttendance);
}
到目前为止,这似乎有效,但我很难理解如何编写删除方法,其中学生和他的出勤之间的“链接”被删除。
我小组中的某个人想出了这个,但我们确信它不会起作用,但这是我们能想到的最好的
public void DeletePersoon(Person person) {
PersonAttendance personAttendance = new PersonAttendance {
Person = person,
Attendance = this,
AttendanceId = this.AttendanceId,
PersonId = person.PersonId
};
PersonAttendance.Remove(personAttendance);
}
解决方案
首先,您需要从数据库中读取所需的对象,然后尝试将其删除。
如果您有一个实体PersonAttendance
(显然是您的情况):
var pa = db.PersonAttendance.Where(p => p.PersonId == 1 && p.AttendenceId == 5).FirstOrDefault();
db.PersonAttendance.Remove(pa);
db.SaveChanges();
否则:
var att = db.Attendance.Where(a => a.Id == 5).FirstOrDefault();
person.Attendence.Remove(att)
db.SaveChanges();