Create relationship with a property inside owned Entity causes an error

c# entity-framework-core

Question

I have an entity that has owned type and i want to create relationship with another entity but the foreign key property exist on the owned type example:- This is my employee entity

public sealed class Employee : AuditedAggregateRoot
{
     public WorkInformation WorkInformation { get; private set; }
}

and it contains a value Object(Owned Type) called WorkInformation

public class WorkInformation : ValueObject<WorkInformation>
{
    private WorkInformation()
    {

    }
    public int? DepartmentId { get; private set; }
}

and i need to create relationship between Employee and Department

public class Department : AuditedAggregateRoot
{

}

and I use the following Fluent configuration to do that but i got an error

  builder.OwnsOne(e => e.WorkInformation)  

 //Add Employee Relations
   builder.HasOne<Department>()
   .WithMany()
   .IsRequired(false)
   .HasForeignKey(e => e.WorkInformation.DepartmentId);

and i got this error enter image description here

if i move the DepartmentId to the owner entity, it works fine.

1
1
3/15/2018 11:53:06 AM

Accepted Answer

Owned types (their properties, relationships etc.) cannot be configured via the owner type builder. Instead, use the ReferenceOwnershipBuilder returned by the OwnsOne method:

var workInfomationBuilder = builder.OwnsOne(e => e.WorkInformation);

//Add Employee Relations
workInfomationBuilder.HasOne<Department>()
    .WithMany()
    .IsRequired(false)
    .HasForeignKey(e => e.DepartmentId);
3
3/15/2018 12:45:54 PM


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