gpt4 book ai didi

entity-framework - 保存时EF Core OwnsOne失败

转载 作者:行者123 更新时间:2023-12-04 11:00:26 25 4
gpt4 key购买 nike

我有以下模型:

public class User
{
public Guid Id {get;set;}
public string Username {get;set;}
public string Address Useraddress {get;set;}
}

public class Address
{
public string Street {get;set;}
public string Zipcode {get;set;}
}

我想将 Useraddress中的数据保存到同一 User表中。因此,我在上下文生成器中添加了 OwnsOne配置。
class UserEntityTypeConfiguration : IEntityTypeConfiguration<User>
{
public void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(x => x.Id);
builder.OwnsOne(x => x.UserAddress);
}
}

当我运行迁移工具时,一切似乎都很好。这是生成的迁移脚本的相关部分:
migrationBuilder.CreateTable(
name: "Users",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Username = table.Column<string>(nullable: false),
Useraddress_Street = table.Column<string>(nullable: true),
Useraddress_Zipcode = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Users", x => x.Id);
});

然后,当我稍后尝试添加 User时:
await _dbContext.Users.AddAsync(user);
await _dbContext.SaveChangesAsync();

然后,我得到以下错误:

The entity of 'User' is sharing the table 'Users' with 'User.Useraddress#Address', but there is no entity of this type with the same key value that has been marked as 'Added'



我做错了什么吗?

PS。
我正在使用Entity Framework Core 2.0。

最佳答案

由于EF Core 2.0支持表拆分,因此默认情况下EF Core 2.0会为其拥有的实体创建一个主键作为影子属性,因此UserAddress实例中User属性的值不能为null,必须对其进行定义。

var user = new User
{
Id = Guid.NewGuid(),
Username = "...",
UserAddress = new Address
{
Street = "...",
Zipcode = "..."
}
};

await _dbContext.Users.AddAsync(user);
await _dbContext.SaveChangesAsync();

如果您希望拥有的实体的值为空,则只需定义一个默认实例,即:
var user = new User
{
Id = Guid.NewGuid(),
Username = "...",
UserAddress = new Address()
};

您可以在此处阅读有关拥有实体隐式键的更多信息: https://docs.microsoft.com/en-us/ef/core/modeling/owned-entities#implicit-keys

关于entity-framework - 保存时EF Core OwnsOne失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49370749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com