Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 849
yo2011 Avatar asked Dec 14 '25 18:12

yo2011


1 Answers

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);
like image 150
Ivan Stoev Avatar answered Dec 16 '25 11:12

Ivan Stoev