简体   繁体   English

EF:删除带有桥表的对象

[英]EF: Deleting object with bridge table

I'm trying to keep track of attendances and students. 我试图跟踪出勤率和学生人数。 For this I am using a bridge table. 为此,我使用了桥表。 Students has an ICollection of PersonAttendances (bridgetable and bridgeclass), and Attendance also has an ICollection of personAttendances. 学生有一个PersonAttendances的ICollection(bridgetable和bridgeclass),而Attendance也有一个PersonAttendances的ICollection。

When a person attends a course on a certain date(property of attendance), in the attendance class the addStudent method gets called 当某人在某个日期(出勤属性)参加课程时,在出勤类中,将调用addStudent方法

public void AddPerson(Person person) {
    PersonAttendance personAttendance = new PersonAttendance {   
        Person = person, Attendance = this, 
        AttendanceId = this.AttendanceId, 
        PersonId = person.PersonId 
    };  
    PersonAttendances.Add(personAttendance);
}

So far, this seems to work, but I'm struggling to understand how to write a delete method, where the 'link' between a student and his attendance gets removed. 到目前为止,这似乎可行,但是我正在努力了解如何编写删除方法,其中删除了学生与其出勤之间的“链接”。

Someone in my group came up with this, but we are positive it wouldn't work, but this is the best we could come up with 我们小组中的某个人提出了这个建议,但我们肯定这是行不通的,但这是我们可以提出的最佳建议

public void DeletePersoon(Person person) {
    PersonAttendance personAttendance = new PersonAttendance {
        Person = person,
        Attendance = this,
        AttendanceId = this.AttendanceId,
        PersonId = person.PersonId
    };
    PersonAttendance.Remove(personAttendance);
}

First you need to read the desired object from database and then try remove it. 首先,您需要从数据库中读取所需的对象,然后尝试将其删除。
If you have an Entity for PersonAttendance (apparently your case): 如果您有一个用于PersonAttendance的实体(显然是您的情况):

var pa = db.PersonAttendance.Where(p => p.PersonId == 1 && p.AttendenceId == 5).FirstOrDefault();
db.PersonAttendance.Remove(pa);
db.SaveChanges();

Otherwise: 除此以外:

var att = db.Attendance.Where(a => a.Id == 5).FirstOrDefault();
person.Attendence.Remove(att)
db.SaveChanges();

If the primary key of PersonAttendance is a composite key using PersonId and AttendanceId , you can avoid loading the entity first by attaching an object with the PK properties set and then set the entity state to deleted: 如果PersonAttendance的主键是使用PersonIdAttendanceId的组合键,则可以通过附加一个具有PK属性集的对象,然后将实体状态设置为PersonAttendance来避免加载该实体:

var theCondemned = new PersonAttendance()
{
    PersonId = person.PersonId,
    AttendanceId = this.AttendanceId,
};

PersonAttendances.Attach( theCondemned )
    .State = EntityState.Deleted;

Otherwise @rad is correct - you must first load the entity from DB (to get the PK) to then remove it. 否则@rad是正确的-您必须首先从数据库加载实体(以获取PK),然后再将其删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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