Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserManager throws exception - Unable to track an entity because primary key property 'Id' is null - after upgrading from .Net Core 2.2 to 3.0

I've used the custom implementation of User which is derivated from IdentityUser using Asp.Net Core Identity:

public class AppUser : IdentityUser
    {
        ...
    }

If I call the method:

var identityResult = await UserManager.CreateAsync(user);

I get the error:

System.InvalidOperationException: Unable to track an entity of type 'AppUser' because primary key property 'Id' is null.

It works perfectly with version of Microsoft.AspNetCore.Identity.EntityFrameworkCore - 2.2.0, but after upgrading to 3.0.0 - it doesn't work.

I get same error during testing of the creation of user as well, there I use following UserManager configuration:

https://github.com/aspnet/AspNetCore/blob/c95ee2b051814b787b07f55ff224d03d550aafeb/src/Identity/test/Shared/MockHelpers.cs#L37

like image 832
Jenan Avatar asked Nov 06 '19 12:11

Jenan


1 Answers

There is EF Core 3.0 introduced breaking change String and byte array keys are not client-generated by default which affects entities which use string PK like IdentityUser<string> and IdentityRole<string> and will cause that exception if the PK is not set explicitly.

However the default IdentityUser and IdentityRole classes were also modified to populate the Id property with Guid.NewGuid().ToString() inside class constructors. So normally you shouldn't have that issue except if some code is setting explicitly the Id to null. Anyway, you can switch to old behavior by using the suggestion from the link

Mitigations

The pre-3.0 behavior can be obtained by explicitly specifying that the key properties should use generated values if no other non-null value is set.

e.g. inside context OnModelCreating override, after calling base implementation:

modelBuilder.Entity<AppUser>()
    .Property(e => e.Id)
    .ValueGeneratedOnAdd();
like image 105
Ivan Stoev Avatar answered Oct 20 '22 01:10

Ivan Stoev