'ConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s)
I wanted to achieve the AddorUpdate() using EF Core.
I was trying to add or update while seeding the datbase.
var artist = await GetArtist();
_applicationDbContext.Artists.UpdateRange(artist);
await _applicationDbContext.SaveChangesAsync(default(CancellationToken));
GetArtist
public async Task<IEnumerable<Artist>> GetArtist()
{
var artistPath = Path.Combine(_env.ContentRootPath, @"wwwroot/Db/artist.json");
return await ReadAsync<IEnumerable<Artist>>(artistPath);
}
Entity:
public class Artist
{
public Guid Id { get; set; }
public string Name { get; set; }
}
ReadAsync
private async Task<T> ReadAsync<T>(string filePath)
{
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true
};
using FileStream stream = File.OpenRead(filePath);
return await System.Text.Json.JsonSerializer.DeserializeAsync<T>(stream, options);
}
But got an error as:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: 'Database operation expected to affect 1 row(s) but actually affected 0 row(s).
It seems This only works for AUTOGENERATED keys also mentioned in the comment,
Isn't there a way to AddOrUpdate without an if-else condition when I have GUID as a primary key?.
Json file:
[
{
"id": "f6222771-52dc-42dc-8d7f-922b74830171",
"name": "ABC"
}
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
