gpt4 book ai didi

c# - Entity Framework Core 设置拥有的实体在添加时为空

转载 作者:行者123 更新时间:2023-11-30 15:14:08 29 4
gpt4 key购买 nike

我有下图:

public class Report
{
public Guid Id { get; set; }
public ICollection<EmployeeEntry> EmployeeEntries { get; set; }
}

public class EmployeeEntry
{
public Guid Id { get; set; }
public DateTimeOffset EntryDate { get; set; }
public Address Address { get; set; }
}

public class Address
{
public string City { get; set; }
public string State { get; set; }
}

并且使用 fluentApi,我已将地址配置为 EmployeeEntry 实体拥有的实体,如下所示:

private void ConfigureEmployeeEntry(EntityTypeBuilder<EmployeeEntry> builder)
{
builder.OwnsOne(x => x.Address, w =>
{
w.Property(x => x.City).HasMaxLength(100);
w.Property(x => x.State).HasMaxLength(100);
});
}

但是当我有多个 EmployeeEntry 的相同地址并运行以下代码时:

dbContext.Reports.Add(report);
dbContext.SaveChanges();

我得到以下异常:

The entity of type 'EmployeeEntry' is sharing the table 'report.EmployeeEntries' with entities of type 'EmployeeEntry.Address#Address', but there is no entity of this type with the same key value that has been marked as 'Added'. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values.

正如我注意到的,在 SaveChanges() 之前添加报告后,EF 将 Address 设置为 null

我使用的是最新版本的 EntityFramework 核心。

最佳答案

But when I have the same Address for more than one EmployeeEntry

如果您指的是相同的地址 实例Owned Entity Types 的 EF Core 文档明确声明目前支持它 - 在 Limitations - Current shortcomings 下:

  • Instances of owned entity types cannot be shared by multiple owners (this is a well-known scenario for value objects that cannot be implemented using owned entity types)

因此,要么确保您使用不同的实例(即使具有相同的属性值),要么不使用拥有的实体类型,而是使用常规的实体类型和关系。

关于c# - Entity Framework Core 设置拥有的实体在添加时为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55919201/

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