删除 EF CTP5 中的多条记录

发布于 2024-10-21 02:34:23 字数 399 浏览 4 评论 0原文

我有一个 Person 类:

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

    public int DeptId { get; set; }

    public decimal Salary { get; set; }
}

在数据库中,Id 和 DeptId 都被标记为主键。

我试图从数据库中删除 DeptId 值与 x(输入变量)匹配的所有记录。

如果我像这样访问记录:

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

删除所有此类记录(不使用迭代)的最佳方法是什么?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放血 2024-10-28 02:34:23

因为您的 Person 具有来自 Id 和 DepId 的复杂 PK,所以您的模型应该包含识别关系。在这种情况下,您也可以这样做:

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

这与迭代中删除人员相同,因为 EF 无法批处理命令。它将删除到数据库的单独往返中的每个人。如果部门里真的有很多人,可以这样称呼:

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

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); 
止于盛夏 2024-10-28 02:34:23
people.ToList().ForEach(p => Database.DeleteObject(p));
Database.SaveChanges();
people.ToList().ForEach(p => Database.DeleteObject(p));
Database.SaveChanges();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文