我使用了User
的自定义实现,该实现是使用IdentityUser
从Asp.Net Core Identity
派生的:
public class AppUser : IdentityUser
{
...
}
如果我调用该方法:
var identityResult = await UserManager.CreateAsync(user);
我收到错误:
System.InvalidOperationException:由于主键属性'Id'为null,因此无法跟踪类型为'AppUser'的实体。
它与Microsoft.AspNetCore.Identity.EntityFrameworkCore
-2.2.0
版本完全兼容,但是升级到3.0.0
后-它不起作用。
在创建用户的测试过程中,我也遇到相同的错误,在这里我使用以下UserManager
配置:
string
PK的实体,例如IdentityUser<string>
和IdentityRole<string>
,如果未明确设置PK,将导致该异常。 但是也修改了默认的IdentityUser
和IdentityRole
类,以在类构造函数中使用Id
填充Guid.NewGuid().ToString()
属性。因此,通常,除非某些代码将Id
显式设置为null
,否则您就不会遇到该问题。无论如何,您可以使用链接中的建议切换到旧的行为
缓解措施
3.0之前的行为可以通过明确指定如果未设置其他非空值,则键属性应使用生成的值来获得。
例如调用基本实现后,内部上下文OnModelCreating
中的覆盖:
modelBuilder.Entity<AppUser>()
.Property(e => e.Id)
.ValueGeneratedOnAdd();