实体框架核心:用户和组织之间的多种关系

问题描述:

我有2个用于用户和组织的模型类。

I have 2 model classes for Users and Organizations.

public class User : IdentityUser
{
    [Required]
    public string Name { get; set; }
    [Required]
    public string Surname { get; set; }

    public int? OrganizationID { get; set; }

    public virtual OrgList org { get; set; }
}

public class OrgList
{
    public OrgList()
    {
        employees = new HashSet<User>();
    }

    public int id { get; set; }
    public String name { get; set; }
    public String ownerId { get; set; }

    public virtual ICollection<User> employees { get; set; }
    public virtual User ownerUser { get; set; }
}

用户可以是某个组织的所有者,也可以是该组织的员工组织(但其他员工不能成为组织的所有者)。

User can be owner of some organization and also he is employee of the same organization (But other employees can't be owners of the organization).

首先,我为员工创建了一个关系,并且可以正常工作

First i've created a relationship for employees and it works OK

modelBuilder.Entity<OrgList>(entity =>
{
    entity.HasMany(e => e.employees)
        .WithOne(e => e.org)
        .HasForeignKey(e => e.OrganizationID)
        .OnDelete(DeleteBehavior.SetNull);
}

但是当我尝试为所有者添加另一种关系

but when i try to add another relationship for owner

entity.HasOne(e => e.ownerUser)
    .WithOne(e => e.org)
    .HasForeignKey<OrgList>(e => e.ownerId)
    .OnDelete(DeleteBehavior.Cascade);

我在迁移:


无法在'User.org'和
'OrgList.o之间创建关系wnerUser,因为
OrgList.employees和 User.org之间已经存在关系。导航属性只能
参与单个关系。

Cannot create a relationship between 'User.org' and 'OrgList.ownerUser', because there already is a relationship between 'OrgList.employees' and 'User.org'. Navigation properties can only participate in a single relationship.

我该如何解决?我用 HasOptional() WithOptionalPrincipal()方法找到了EF6(不是EF Core)的答案

How can i fix it? I've found an answers for EF6 (not EF Core) with HasOptional() and WithOptionalPrincipal() methods that not exist in EF Core.

我可以在不为员工创建其他表的情况下,也可以在不创建其他虚拟OrgList 的情况下执行此操作吗?用户类?

Can i do it without creating additional table for employees or without creating additional virtual OrgList on User class?

您正在尝试为拥有相同属性的用户创建所有者关系。员工关系。实体框架不知道分配属性的关系。如果您在用户上创建了另一个属性,例如

You're trying to create the owner relationship with the same property on the user that you are using for the employee relationship. Entity framework wouldn't know which relationship to assign the property. If you created another property on the user like

public int? OwnedOrganizationID { get; set; }
public virtual OrgList OwnedOrg { get; set; }

并将语句更改为

entity.HasOne(e => e.ownerUser)
.WithOne(e => e.OwnedOrg)
.HasForeignKey<OrgList>(e => e.ownerId)
.OnDelete(DeleteBehavior.Cascade);

我想它应该可以工作。