yo2011
yo2011

Reputation: 1021

Create relationship with a property inside owned Entity causes an error

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.

Upvotes: 3

Views: 2072

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205779

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

Upvotes: 5

Related Questions