【问题标题】:UserManager throws exception - Unable to track an entity because primary key property 'Id' is null - after upgrading from .Net Core 2.2 to 3.0UserManager 抛出异常 - 无法跟踪实体,因为主键属性“Id”为空 - 从 .Net Core 2.2 升级到 3.0 后
【发布时间】:2020-03-02 21:55:28
【问题描述】:

我使用了User 的自定义实现,它是从IdentityUser 派生的Asp.Net Core Identity

public class AppUser : IdentityUser
    {
        ...
    }

如果我调用方法:

var identityResult = await UserManager.CreateAsync(user);

我得到错误:

System.InvalidOperationException:无法跟踪“AppUser”类型的实体,因为主键属性“Id”为空。

它与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

【问题讨论】:

  • 检查是否user.Id == null。有一个与字符串键相关的breaking change in EF Core 3.0,但是3.0 中的IdentityUser 类在构造函数中将Id 设置为Guid.NewGuid().ToString()。因此,您要么使用旧的身份类,要么将 Id 显式设置为 null,,要么不继承 IdentityUser,而是继承 IdentityUser<string>
  • User.Id 为空,但它适用于 .net core 2.2。你有什么修复它的建议?
  • 好吧,确保它不为空。或者使用中断更改链接中的建议 - 在 Mitigations 下可以通过...获得 3.0 之前的行为...
  • 你是对的,你能把你的小费像答案一样吗?我会接受的。我通过正确的映射解决了这个问题。谢谢。

标签: asp.net-core entity-framework-core asp.net-core-identity


【解决方案1】:

EF Core 3.0 引入了重大更改 String and byte array keys are not client-generated by default,它会影响使用 string PK 的实体,例如 IdentityUser<string>IdentityRole<string>,如果未明确设置 PK,则会导致该异常。

但是,默认的 IdentityUserIdentityRole 类也被修改为在类构造函数中使用 Guid.NewGuid().ToString() 填充 Id 属性。所以通常你不应该有这个问题,除非某些代码明确地将Id 设置为null。无论如何,您可以使用链接中的建议切换到旧行为

缓解措施

如果没有设置其他非空值,则可以通过显式指定键属性应使用生成的值来获得 3.0 之前的行为。

例如在调用基本实现之后,在上下文 OnModelCreating 覆盖:

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

【讨论】:

  • 谢谢。我当时想“这到底是怎么回事!?”
猜你喜欢
  • 2020-03-26
  • 2021-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 1970-01-01
  • 2020-01-29
  • 1970-01-01
相关资源
最近更新 更多