代码之家  ›  专栏  ›  技术社区  ›  Simple Code

实体框架核心设置添加时拥有的实体为空

  •  0
  • Simple Code  · 技术社区  · 7 年前

    我有以下图表:

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

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

    但是当我有一个以上相同的地址

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

    我得到了以下例外:

    "报告。EmployeeEntries'具有类型为的实体 “雇员入境。地址#Address',但不存在此类型的实体 具有已标记为“已添加”的相同键值。考虑 使用“DbContextOptionsBuilder”。启用SensitiveDatalogging'以查看 关键值。

    SaveChanges() EF将地址设为 null .

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

    0 回复  |  直到 7 年前
        1
  •  6
  •   Ivan Stoev    7 年前

    但是当我有一个以上雇员的相同地址时

    如果你的意思是一样的 Address 例子 ,EF核心文档 Owned Entity Types 明确声明它是 目前支持-在 Limitations - Current shortcomings :

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