我正在使用ef core 2.1,数据结构如下;
public class EmployeeEntity : BaseEntity
{
public string EmployeeNo { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public int? Status { get; set; }
public virtual Guid? OrganizationId { get; set; }
public virtual OrganizationEntity Organization { get; set; }
}
public class OrganizationEntity : BaseEntity
{
public string Text { get; set; }
public Guid? ParentOrganizationId { get; set; }
public virtual OrganizationEntity ParentOrganization { get; set; }
public virtual Guid? ManagerId { get; set; }
public virtual EmployeeEntity Manager { get; set; }
public virtual ICollection<OrganizationEntity> ChildOrganizations { get; set; }
public virtual ICollection<EmployeeEntity> Employees { get; set; }
}
private void ConfigureOrganization(EntityTypeBuilder<OrganizationEntity> builder)
{
builder.ToTable("Organization");
builder.HasMany(o => o.Employees).WithOne(e => e.Organization).HasForeignKey(f => f.OrganizationId).OnDelete(DeleteBehavior.Restrict);
builder.HasMany(o => o.ChildOrganizations).WithOne(o => o.ParentOrganization).HasForeignKey(o => o.ParentOrganizationId)
.OnDelete(DeleteBehavior.ClientSetNull);
}
private void ConfigureEmployee(EntityTypeBuilder<EmployeeEntity> builder)
{
builder.ToTable("Employee");
builder.HasOne(e => e.Organization).WithMany(o => o.Employees).HasForeignKey(e => e.OrganizationId).OnDelete(DeleteBehavior.Restrict);
}
有了这个,我意识到我的Employee表上还有一个额外的OrganizationEntityId列,所以我尝试了下面的conf来解决这个问题。
private void ConfigureOrganization(EntityTypeBuilder<OrganizationEntity> builder)
{
builder.ToTable("Organization");
builder.HasOne(o => o.Manager).WithOne(e => e.Organization).HasForeignKey<EmployeeEntity>(e => e.OrganizationId).OnDelete(DeleteBehavior.SetNull);
builder.HasMany(o => o.Employees).WithOne(e => e.Organization).HasForeignKey(e => e.OrganizationId).OnDelete(DeleteBehavior.SetNull);
builder.HasMany(o => o.ChildOrganizations).WithOne(o => o.ParentOrganization).HasForeignKey(o => o.ParentOrganizationId)
.OnDelete(DeleteBehavior.ClientSetNull);
}
private void ConfigureEmployee(EntityTypeBuilder<EmployeeEntity> builder)
{
builder.ToTable("Employee");
}
但是通过这种配置,我得到了
无法在'OrganizationEntity.Employees'之间建立关系 和“ EmployeeEntity.Organization”,因为已经有一个 'OrganizationEntity.Manager'与 “ EmployeeEntity.Organization”。导航属性只能 参加单一关系
什么是正确的配置以提供可靠的关系并在表上提供正确的列? 我愿意改变数据结构。
注意:数据结构的语言对等是;