什么是推荐的做法是在的EntityFramework更新或删除多个实体?是在、多个、或删除、实体

2023-09-03 04:41:27 作者:云里有鹤

在SQL人们可能有时写点东西像

In SQL one might sometimes write something like

DELETE FROM table WHERE column IS NULL

UPDATE table SET column1=value WHERE column2 IS NULL

或可能适用于多行的所有其他标准。

or any other criterion that might apply to multiple rows.

据我所知道的,最好的EntityFramework可以做的是一样的东西。

As far as I can tell, the best EntityFramework can do is something like

foreach (var entity in db.Table.Where(row => row.Column == null))
    db.Table.Remove(entity);   // or entity.Column2 = value;
db.SaveChanges();

当然,这会检索所有实体,然后运行对每个单独的DELETE查询,但。一定必须是,如果存在满足该​​标准许多实体要慢得多。

But of course that will retrieve all the entities, and then run a separate DELETE query for each. Surely that must be much slower if there are many entities that satisfy the criterion.

因此​​,削减长话短说,就是那里的EntityFramework在单个查询更新或删除多个实体提供任何支持?

So, cut a long story short, is there any support in EntityFramework for updating or deleting multiple entities in a single query?

推荐答案

EF没有用于批量更新或者删除支持,但你可以简单地做:

EF doesn't have support for batch updates or deletes but you can simply do:

db.Database.ExecuteSqlCommand("DELETE FROM ...", someParameter);

编辑:

人谁真的想与LINQ查询坚持有时使用的解决办法,他们首先创建LINQ查询选择SQL查询:

People who really want to stick with LINQ queries sometimes use workaround where they first create select SQL query from LINQ query:

string query = db.Table.Where(row => row.Column == null).ToString();

和后找到第一个出现的替换查询开始删除和执行结果与 ExecuteSqlCommand 。这种方法的问题是,它只能在基本方案。它不会与实体分割或者你需要为每个实体删除两个或两个以上的记录一些继承映射工作。

and after that find the first occurrence of FROM and replace the beginning of the query with DELETE and execute result with ExecuteSqlCommand. The problem with this approach is that it works only in basic scenarios. It will not work with entity splitting or some inheritance mapping where you need to delete two or more records per entity.