相同表之间的一对一和一对多关系

时间:2019-09-20 05:59:40

标签: c# entity-framework-core ef-core-2.1

我正在使用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”。导航属性只能   参加单一关系

什么是正确的配置以提供可靠的关系并在表上提供正确的列? 我愿意改变数据结构。

注意:数据结构的语言对等是;

  • 一个组织有很多员工。
  • 员工可能属于组织或任何组织
  • 组织可以有经理(雇员)或其他任何人

0 个答案:

没有答案