Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

like image 901
Simple Code Avatar asked Sep 23 '26 20:09

Simple Code


1 Answers

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.

like image 85
Ivan Stoev Avatar answered Sep 28 '26 22:09

Ivan Stoev