[英]Entity Framework Core setting owned entity null when added
I have the following graph: 我有以下图表:
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; }
}
And using fluentApi I have configured Address as owned entity by EmployeeEntry
entity like the following: 并且使用fluentApi我已将
EmployeeEntry
实体的Address配置为拥有实体,如下所示:
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);
});
}
But when I have the same Address for more than one EmployeeEntry
and running the following code: 但是当我有多个
EmployeeEntry
的相同地址并运行以下代码时:
dbContext.Reports.Add(report);
dbContext.SaveChanges();
I got the following exception: 我得到以下异常:
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'.
类型为“EmployeeEntry”的实体正在与“EmployeeEntry.Address#Address”类型的实体共享表“report.EmployeeEntries”,但是没有此类型的实体具有标记为“已添加”的相同键值。 Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values.
考虑使用'DbContextOptionsBuilder.EnableSensitiveDataLogging'来查看键值。
As I noticed that after adding the report before SaveChanges()
EF makes Address as null
. 我注意到在
SaveChanges()
之前添加报告后,EF使Address为null
。
I am using the latest version of the EntityFramework core. 我使用的是最新版本的EntityFramework核心。
But when I have the same Address for more than one EmployeeEntry
但是当我拥有多个EmployeeEntry的相同地址时
If you mean the same Address
instance , EF Core documentation for Owned Entity Types explicitly states that it's not currently supported - under Limitations - Current shortcomings : 如果你指的是同一个
Address
的实例 ,为EF核心文档拥有的实体类型明确指出,它目前还不支持-下限制-目前的不足之处 :
- 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)
多个所有者无法共享拥有实体类型的实例(这是无法使用拥有的实体类型实现的值对象的众所周知的方案)
So either make sure you use different instances (even with the same property values), or don't use owned entity types, but regular entity types and relationships. 因此要么确保使用不同的实例(即使具有相同的属性值),要么不使用拥有的实体类型,而是使用常规实体类型和关系。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.