开发者

Deleting multiple records in EF CTP5

开发者 https://www.devze.com 2023-02-16 00:04 出处:网络
I have a Person class: public class Person { public int Id { get; set; } public int DeptId { get; set; }

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.Pe开发者_运维问答ople.Where(p => p.DeptId = 10);

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


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); 


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

精彩评论

暂无评论...
验证码 换一张
取 消