c# - 无法跟踪类型实体,因为主键属性 'id' 为空

标签 c# asp.net asp.net-core entity-framework-core

升级到 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/

相关文章:

.net - 如何检测 .Net 应用程序类型?

jquery - 调整大小时弹出警报离开屏幕

asp.net-core - 如何将依赖注入(inject)与 .NET Core 2 API 选项结合使用?

c# - 如何通过 C# 将 NULL 值传递给存储过程

c# - 将一个整数表示为其他一些固定整数的总和

c# - 无法将 View 数据下拉列表的选定值获取到我的 Controller 操作?

asp.net - 使用表单例份验证在 ASP.NET Web 表单中进行路由

asp.net - Azure KeyVault 突然出现 System.Net.Http.HttpRequestException

asp.net-core - aspnet核心应用程序中的Autofac.Multitenant似乎无法正确解析租户范围的依赖关系

c# - 如何简化行进方 block 网格?