使用拥有的实体内部的属性创建关系会导致错误 [英] 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; }
}
它包含一个名为WorkInformation的对象(拥有的类型)
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
{
}
,我使用以下Fluent配置执行此操作,但出现错误
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
如果我将DepartmentId移到所有者实体,则可以正常工作。
if i move the DepartmentId to the owner entity, it works fine.
推荐答案
拥有的类型(它们的属性,关系等)无法通过拥有者类型构建器进行配置。而是使用 OwnsOne
方法返回的 ReferenceOwnershipBuilder
:
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);
这篇关于使用拥有的实体内部的属性创建关系会导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!