问题描述
我使用了User
的自定义实现,该实现是使用Asp.Net Core Identity
从IdentityUser
派生的:
I've used the custom implementation of User
which is derivated from IdentityUser
using Asp.Net Core Identity
:
public class AppUser : IdentityUser
{
...
}
如果我调用该方法:
var identityResult = await UserManager.CreateAsync(user);
我得到了错误:
它与Microsoft.AspNetCore.Identity.EntityFrameworkCore
-2.2.0
版本完全兼容,但是升级到3.0.0
后-它不起作用.
It works perfectly with version of Microsoft.AspNetCore.Identity.EntityFrameworkCore
- 2.2.0
, but after upgrading to 3.0.0
- it doesn't work.
在测试用户创建过程中,我也遇到相同的错误,在这里我使用以下UserManager
配置:
I get same error during testing of the creation of user as well, there I use following UserManager
configuration:
推荐答案
引入了EF Core 3.0重大更改字符串和字节数组键不是客户端-默认情况下生成的,会影响使用string
PK的实体(例如IdentityUser<string>
和IdentityRole<string>
),如果未明确设置PK,则会导致该异常.
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.
但是,还修改了默认的IdentityUser
和IdentityRole
类,以在类构造函数中使用Guid.NewGuid().ToString()
填充Id
属性.因此,通常,除非某些代码将Id
显式设置为null
,否则您就不会遇到该问题.无论如何,您可以使用链接中的建议来切换到旧的行为
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
如果未设置其他非空值,则可以通过明确指定键属性应使用生成的值来获得3.0之前的行为.
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
中进行覆盖:
e.g. inside context OnModelCreating
override, after calling base implementation:
modelBuilder.Entity<AppUser>()
.Property(e => e.Id)
.ValueGeneratedOnAdd();
这篇关于从.Net Core 2.2升级到3.0后,UserManager引发异常-无法跟踪实体,因为主键属性'Id'为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!