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

旧城冷巷雨未停 提交于 2019-12-22 14:52:37

问题


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


回答1:


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();


来源:https://stackoverflow.com/questions/58729749/usermanager-throws-exception-unable-to-track-an-entity-because-primary-key-pro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!