Owned entities with collection relationships using entity framework core

entity-framework-core

Question

I am trying to model the following class structure where PersonDetails is an owned entity using table splitting i.e. there is no table in the db schema called PersonDetails

I am using entity framework core 2.2

public class Person
{
  public long Id { get; set; }
  public PersonDetails Details { get; set; }
}

public class PersonDetails
{
  public IReadOnlyCollection<Address> Addresses { get; set; }
  public IReadOnlyCollection<Contact> Contacts { get; set; }
}

public class Address
{
  public string Street { get; set; }
  public string Suburb { get; set; }
}

public class Contact
{
  public string PhoneNumber { get; set; }
  public string EmailAddress { get; set; }
}

The entity type maps appear as follows:

public class PersonTypeConfiguration : IEntityTypeConfiguration<Person>
{
  public void Configure(EntityTypeBuilder<Person> builder)
  {
    builder.Property(p => p.Id).ValueGeneratedOnAdd();
    builder.OwnsOne(p => p.Details, b =>
    {
      b.HasMany(p => p.Addresses).WithOne().OnDelete(DeleteBehavior.Cascade);
      b.HasMany(p => p.Contacts).WithOne().OnDelete(DeleteBehavior.Cascade);
    });
  }
}

public class AddressTypeConfiguration : IEntityTypeConfiguration<Address>
{
  public void Configure(EntityTypeBuilder<Address> builder)
  {
    builder.Property<string>("Id").ValueGeneratedOnAdd();
  }
}

public class ContactTypeConfiguration : IEntityTypeConfiguration<Contact>
{
  public void Configure(EntityTypeBuilder<Contact> builder)
  {
    builder.Property<int>("Id").ValueGeneratedOnAdd();
  }
}

This configuration throws the following error:

'The relationship from 'Address' to 'PersonDetails.Addresses' is not supported because the owned entity type 'PersonDetails' cannot be on the principal side of a non-ownership relationship.'

Is this mapping supported in EF core? I was not able to find this in the docs but perhaps I missed it.

If it's not supported does anyone know if there are plans to support it?

A full sample can be found here https://github.com/RossJayJones/entity-framework-core-samples

1
2
8/17/2019 12:44:40 AM

Popular Answer

This is not supported by design. Owned types are part of an aggregate and only the aggregate root can be referenced from outside.

You can still have the same classes and use table splitting, just don't configure PersonDetails as owned.

0
8/9/2019 4:49:37 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