0

想象一下,我有一个包含以下列和值的 SQL 表:

+----+---------+------------+---------+------------+
| ID | Status1 | Condition1 | Status2 | Condition2 |
+----+---------+------------+---------+------------+
|  1 |       1 |          1 |       1 |          1 |
|  2 |       1 |          0 |       1 |          1 |
|  3 |       1 |          1 |       1 |          0 |
|  4 |       1 |          0 |       1 |          0 |
+----+---------+------------+---------+------------+

我想分别根据 Condition1 和 Condition2 中的值更新 Status1 和 Status2 的值。

我的 SQL 语句如下所示:

UPDATE
    myTable
SET
    Status1 = CASE Condition1
                WHEN 1 THEN 3
                ELSE 4
            END,
    Status2  = CASE Condition2
                WHEN 1 THEN 3
                ELSE 4
            END
WHERE
    ID = @targetRowID

如果我对每个 ID 的表单独运行上述 SQL 语句,我将得到以下值:

+----+---------+------------+---------+------------+
| ID | Status1 | Condition1 | Status2 | Condition2 |
+----+---------+------------+---------+------------+
|  1 |       3 |          1 |       3 |          1 |
|  2 |       4 |          0 |       3 |          1 |
|  3 |       3 |          1 |       4 |          0 |
|  4 |       4 |          0 |       4 |          0 |
+----+---------+------------+---------+------------+

在 Entity Framework 中,我通过执行以下操作进行相同类型的更新:

var  myRow = dbContext.myTable.Single(r => r.ID == 1);

myRow.Status1 = (myRow.Condition1 == 1) ? 3 : 4;
myRow.Status2 = (myRow.Condition2 == 1) ? 3 : 4;

dbContext.SaveChanges();

这可行,但它首先从数据库中获取数据,然后进行第二次查询以进行更新。是否可以像上面的普通 SQL 代码那样一次性完成更新?

4

1 回答 1

2

LINQ 总是在更新之前进行查询。这是该技术众所周知的烦恼。

(nit-pick: "This works, but it first fetches the data from the database and then does a second query to do the update." The second thing send to the database is not a "query". A "query" is standard English is a question, hence a database query is a request for information, i.e., a SELECT statement. An UPDATE is a command.)

于 2012-12-07T23:02:43.407 回答