UserManager 抛出异常 - 无法跟踪实体,因为主键 属性 'Id' 为空 - 从 .Net Core 2.2 升级到 3.0 后

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

我使用了 User 的自定义实现,它使用 Asp.Net Core Identity:

IdentityUser 派生而来
public class AppUser : IdentityUser
    {
        ...
    }

如果我调用方法:

var identityResult = await UserManager.CreateAsync(user);

我收到错误:

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

它与 Microsoft.AspNetCore.Identity.EntityFrameworkCore - 2.2.0 版本完美配合,但在升级到 3.0.0 后 - 它不起作用。

我在测试创建用户的过程中也遇到了同样的错误,我使用了以下 UserManager 配置:

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

EF Core 3.0 引入了重大变更 String and byte array keys are not client-generated by default,它会影响使用 string PK 的实体,如 IdentityUser<string>IdentityRole<string>,如果 PK 是没有明确设置。

但是默认的 IdentityUserIdentityRole classes 也被修改为填充 Id 属性 和 Guid.NewGuid().ToString() inside class 构造函数。所以通常你不应该有这个问题,除非某些代码明确地将 Id 设置为 null。无论如何,您可以使用 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.

例如内部上下文 OnModelCreating 覆盖,调用基础实现后:

modelBuilder.Entity<AppUser>()
    .Property(e => e.Id)
    .ValueGeneratedOnAdd();