Entity Framework Core setting owned entity null when added

c# entity-framework-core

Question

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:

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:

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'. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values.

As I noticed that after adding the report before SaveChanges() EF makes Address as null.

I am using the latest version of the EntityFramework core.

1
3
4/30/2019 11:07:15 AM

Accepted Answer

But when I have the same Address for more than one 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:

  • 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.

4
4/30/2019 10:49:34 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow