kidoman
kidoman

Reputation: 2422

Deleting multiple records in EF CTP5

I have a Person class:

public class Person {
    public int Id { get; set; }

    public int DeptId { get; set; }

    public decimal Salary { get; set; }
}

In the database both Id and DeptId are marked as primary key.

I was trying to delete all records from the database where the DeptId value matches x (an input variable.)

If I access the records like this:

var people = Database.People.Where(p => p.DeptId = 10);

What is the best way to delete all such records (without using iteration)?

Upvotes: 0

Views: 1659

Answers (2)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

Because your Person has complex PK from Id and DepId your model should contain identifying relation. In such case you can also do this:

var dep = Database.Departments
                  .Include(d => d.People)
                  .Where(d => d.Id == 10)
                  .Single();
dep.People.Clear();
Database.SaveChanges();

It will be the same as deleting people in iteration because EF is not able to batch commands. It will delete each person in separate roundtrip to DB. If you have really lot of people in department call this:

Database.Database.SqlCommand("DELETE FROM People WHERE DepId = {0}", 10); 

Upvotes: 2

Bala R
Bala R

Reputation: 108957

people.ToList().ForEach(p => Database.DeleteObject(p));
Database.SaveChanges();

Upvotes: 1

Related Questions