M
M
mletov2021-02-03 14:10:33
SQL
mletov, 2021-02-03 14:10:33

How to make group update in entity framework so as not to break constarint?

Please, prompt

There is a table, in it there is a field, with restriction UNIQUE.
I need to update this table.
If everything is done in pure sql, then there is no problem, because the update occurs in one request.
But through EF it doesn’t work, because the lines are updated one by one.

Example:
The year field is unique. I want to put 2019 in the entry where 2020 stood, and vice versa, in short, swap places.
Here is a working example in sql.

UPDATE table
SET year = (CASE WHEN year = 2019 THEN 2020 WHEN year = 2020 THEN 2019 END)
WHERE year IN (2019, 2020)


But this will not work in ef, because all updates go sequentially, and not all at once, even if context.SaveChanges() is called only once at the very end. We update the line = 2020, but since there is already a record with a unique 2020, then quite naturally we get an error.

NetFramework 6.2.0, not Core.

The option with deleting old records and inserting new ones is not suitable, because other tables can be tied to the entity.

Is there a mechanism to update everything at once through ef?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-02-03
@vabka

Emnip, EF does not allow updating many records with one request. use sql

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question