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);
if i move the DepartmentId to the owner entity, it works fine.
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);