SKale
SKale

Reputation: 471

Using LINQ to delete multiple rows in table using matching key from related table

Suppose I have models (and tables) that look like below:

Program: ProgramId (PKey)
ProgramRegistration: ProgramRegistrationId (PKey), ProgramId (FKey)
CourseEnrollments: CourseEnrollmentId (PKey), ProgramRegistrationId (FKey)

What I need to do is that in a controller I am passing an id that happens to be the ProgramId. I want to bulk delete all rows (or items) in CourseEnrollments that have a matching record in ProgramRegistration with the passed parameter id = ProgramId.

So I figured I would do:

db.CourseEnrollments.Where(e => e.ProgramRegistration.ProgramId == id).ToList().Remove();

Question: Is the above approach of using navigation properties correct?

Upvotes: 0

Views: 5321

Answers (1)

SKale
SKale

Reputation: 471

I solved it in the following manner instead:

var results = from c in vm.CourseEnrollments
              where c.ProgramRegistration.ProgramId == id
              select c;

foreach (var courseenrollment in results)
{
    db.CourseEnrollments.Remove(courseenrollment);
}
db.SaveChanges();

Upvotes: 2

Related Questions