由于主键属性"id"为空,因此无法跟踪类型的实体 [英] Unable to track an entity of type because primary key property 'id' is null

查看:1058
本文介绍了由于主键属性"id"为空,因此无法跟踪类型的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

升级到Asp.Net Core 3.0后,尝试创建用户时,我的Identity类收到以下错误:

After I upgraded to Asp.Net Core 3.0 I am getting the following error for my Identity class when attempting to create a user:

由于主键属性,无法跟踪类型为用户"的实体 'id'为空.

Unable to track an entity 'User' of type because primary key property 'id' is null.

此处用户代表我对身份模型的扩展.

Here User represents my extension of the Identity model.

这是发生错误的代码行:

This is the line of code where the error occurs:

var result = await _userManager.CreateAsync(user, password);

推荐答案

这是由于EF Core 3.0中的重大更改所致,该更改可以在以下链接中找到:

This is due to breaking changes in EF Core 3.0 which can be found under this link:

https://docs.microsoft.com/zh-cn/ef/core/what-is-new/ef-core-3.0/默认情况下,不是由客户端生成中断更改#string和字节数组键的键

可以通过手动分配密钥来解决此问题:

The problem can be solved by assigning a key manually like this:

// assign GUID to Id
user.Id = Guid.NewGuid().ToString();
var result = await _userManager.CreateAsync(user, password);

根据微软的说法,另一种解决方案是

Another solution would be the following according to Microsoft:

3.0之前的行为可以通过明确指定 如果没有其他非空值,则关键属性应使用生成的值 设置好了.例如,使用流畅的API:

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; }

这篇关于由于主键属性"id"为空,因此无法跟踪类型的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆