Order of SQL CRUD operations in Entity Framework Core

George Parissis 1 Reputation point
2021-04-14T14:30:08.76+00:00

Many people have asked this question, but I am referring to something different. I have a table that stores facts. And this table contains the below columns.

CREATE TABLE [dbo].[XTABLE]
(
[identity] nvarchar(50) not null
[seq] int not null identity,
[valid_from] datetime2(0) not null,
[valid_to] datetime2(0) not null,
[user] nvarchar(50) not null,
[.......]
constraint [pk] primary key ([seq])
)

go

create unique index [latest_by_identity] on [dbo].XTABLE where [valid_to] = '9999-12-31'

Now imagine the below record:

ATXF8 | 1 | 2021-01-01 | 9999-12-31 | ....

And think about the scenario where I receive a new fact (record) with the same identity (ATXF8). What I need to do in the application is:

  1. Fetch the last valid fact.
  2. Update the [valid_to] field with the current date.
  3. Create a new fact record and attach to DbContext.
  4. Set the [valid_from] to be one second after the value [valid_to] from step 2.
  5. Set the value of [valid_to] to be 9999-12-31.
  6. Call the SaveChanges()

It turns out that the commands in the database can't be executed because EF Core is executing first the insert and because of the index I get an exception.
Is there anyway to control EF Core for this scenario to execute first the update and after the insert?
If not what other alternatives do I have? Create a transaction and call SaveChanges() twice?

Thank you,
George

Entity Framework Core
Entity Framework Core
A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
743 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Daniel Zhang-MSFT 9,626 Reputation points
    2021-04-15T06:13:32.343+00:00

    Hi GeorgeParissis-9878,
    Did you change the state of the entity after you attached it?
    Please refer to this thread.
    And double check setting updating the status as Added Or Modified.
    You can set the EntityState of the newly attached entity to Modified manually.

    context.Entry(yourEntity).State = EntityState.Modified;  
    

    More details please refer to this document.
    If not successful, please provide some related code.
    Best Regards,
    Daniel Zhang


    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.