Does EF Core 5 support explicit setting of a guid primary key?
See original GitHub issueI have a code base that was upgrade recently from .NET Core 2.2 to .NET 5 and just noticed an issue that setting an entity’s primary key before save is throwing exception.
According to this documentation https://docs.microsoft.com/en-us/ef/core/modeling/generated-properties?tabs=data-annotations#overriding-value-generation it seems like it should be supported, but when I try I get the following exception:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.```
Before .NET 5 setting the primary key explicitly worked with no additional configuration in the db context. I’ve tried configuring primary keys as shown below but still not having any success
var md = propertyBuilder.HasDefaultValueSql("uuid_generate_v1mc()")
.ValueGeneratedOnAdd()
.Metadata;
md.SetAfterSaveBehavior(PropertySaveBehavior.Throw);
md.SetBeforeSaveBehavior(PropertySaveBehavior.Save);
Below is a simple example of trying to add a new entity to a navigation property of another entity
entity.PropertyValues.Add(
new PropertyValue
{
Id = RT.Comb.Provider.PostgreSql.Create(),
Value = "some random value",
DisplaySequence = 100
});
Is this possible to set primary keys explicitly?
Include provider and version information
EF Core version: 5.0.5 Database provider: (Npgsql.EntityFrameworkCore.PostgreSQL Version=“5.0.5.1”) Target framework: (NET 5.0) Operating system: Windows 10 IDE: ( Visual Studio 2019 16.9.4)
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (3 by maintainers)
The problem is that EF Core treats this as an update of an existing Topic instead of an insertion of a new one. If I change your code fragment to the following, everything works:
This doc page should shed some light on the interaction between generated/explicit keys and addition/insertion (/cc @ajcvickers).
Thanks @roji and @ajcvickers, I was able to work around it by passing the Db context to the method where the adding occurs which can add it to the DB set before adding to the collection.
Ideally I wouldn’t want to pass around the DB context like that, but understand why I need to because of the concurrency check now.