Ranga
Ranga

Reputation: 1391

EF Core - data may have been modified or deleted since entities were loaded with SQL ON UPDATE CURRENT_TIMESTAMP

I'm getting "data may have been modified or deleted since entities were loaded" exception while trying to update the same record for the second time. I found the issue is because I'm using the below column definition in MySQL and it seems I'm not handling this correctly in my entities.

last_updated_at datetime(6) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

dbItem.LastUpdatedAt = DateTime.Now;

If I update the value from my entity as above and save then it works.

But if I don't update the value from my entity it doesn't work for the second update throwing "data may have been modified or deleted since entities were loaded" exception

What would be a good solution for this.

Upvotes: 1

Views: 1587

Answers (1)

grek40
grek40

Reputation: 13448

What you want is, that EF will get the updated value back from database at the end of an add/update operation. You can use ValueGeneratedOnAddOrUpdate configuration to achieve this.

Contrary to what the name suggests, you are still allowed to provide your own value that will be included in the context - just make sure that you don't try to provide the C# default value if you want to transfer the value to the database

If you set a value for the property configured as ValueGeneratedOnAddOrUpdate while the entity is being tracked by the context, the property and the value that you set will be included in any INSERT and UPDATE statements. This value may be saved in the database, depending on how you have configured your value generation strategy. This is only applicable if the value that you provide is not the CLR default value for the data type of the property.

Quoted from https://www.learnentityframeworkcore.com/configuration/fluent-api/valuegeneratedonaddorupdate-method

Disclaimer: I never tried this practically. It's just what I assume to work after reading some docs.

Upvotes: 1

Related Questions