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

查看:22
本文介绍了无法跟踪类型的实体,因为主键属性“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.

这里 User 代表我对 Identity 模型的扩展.

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/en-us/ef/core/what-is-new/ef-core-3.0/中断更改#string-and-byte-array-keys-are-not-client-generated-by-default

这个问题可以通过像这样手动分配一个键来解决:

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 之前的行为可以通过明确指定如果没有其他非空值,关键属性应使用生成的值设置.例如,使用 fluent 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天全站免登陆