Pregunta

Imagine I have a SQL table with the following columns and values:

+----+---------+------------+---------+------------+
| 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 |
+----+---------+------------+---------+------------+

I want to update the values of Status1 and Status2 depending on the values in Condition1 and Condition2 respectively.

My SQL statement would look like this:

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

If I were to run the above SQL statement against the table for each ID indiviually, I would wind up with the following values:

+----+---------+------------+---------+------------+
| 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 |
+----+---------+------------+---------+------------+

In Entity Framework, I do the same kind of update by doing this:

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

This works, but it first fetches the data from the database and then does a second query to do the update. Is it possible to do the update all in one shot like the plain SQL code above does?

¿Fue útil?

Solución

LINQ always does a query before an update. This is a well-known annoyance of the technology.

(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.)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top