question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Does EF Core 5 support explicit setting of a guid primary key?

See original GitHub issue

I 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:closed
  • Created 2 years ago
  • Comments:5 (3 by maintainers)

github_iconTop GitHub Comments

1reaction
rojicommented, May 13, 2021

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:

var topic = new Topic
{
    Id = Guid.NewGuid(),
    Name = "Testing"
};
ctx.Topics.Add(topic); // <-- note this
trackedManualBlog.Topics.Add(topic);

This doc page should shed some light on the interaction between generated/explicit keys and addition/insertion (/cc @ajcvickers).

0reactions
bmcdavidepicommented, May 13, 2021

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.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Keys - EF Core
While EF Core supports using properties of any primitive type as the primary key, including string , Guid , byte[] and others, ...
Read more >
Generated Values - EF Core
Explicitly configuring value generation​​ We saw above that EF Core automatically sets up value generation for primary keys - but we may want...
Read more >
How does Entity Framework generate a GUID for a primary ...
The GUID is not generated by Entity Framework nor by SQL . It is handled by Identity framework. Just navigate to IdentityModels.cs
Read more >
c# - Using a GUID as a Primary Key
Yes you can use GUID as primary key. The down side is size and rapid fragmentation of the index. Unless you need uniqueness...
Read more >
Value generation on add failing for GUID · Issue #10070
I believe I have stumbled across a bug. Using EntityFrameworkCore 2.0, I am trying to set up a table that has a primary...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found