升级到 Asp.Net Core 3.0 后,尝试创建用户时,我的 Identity 类出现以下错误:
Unable to track an entity 'User' of type because primary key property 'id' is null.
这里 User 代表我对 Identity 模型的扩展。
这是发生错误的代码行:
var result = await _userManager.CreateAsync(user, password);
最佳答案
这是由于 EF Core 3.0 中的重大更改,可在此链接下找到:
https://docs.microsoft.com/en-us/ef/core/what-is-new/ef-core-3.0/breaking-changes#string-and-byte-array-keys-are-not-client-generated-by-default
该问题可以通过手动分配一个键来解决,如下所示:
// assign GUID to Id
user.Id = Guid.NewGuid().ToString();
var result = await _userManager.CreateAsync(user, password);
根据微软的说法,另一种解决方案如下:
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. For example, with the fluent API:
modelBuilder
.Entity<Blog>()
.Property(e => e.Id)
.ValueGeneratedOnAdd();
或使用数据注释:
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public string Id { get; set; }
关于c# - 无法跟踪类型实体,因为主键属性 'id' 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59134406/