Entity Framework Core: Multiple Relationships between Users and Organizations

空扰寡人 提交于 2019-12-13 00:44:29

问题


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);

i have an error on migration:

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.

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.

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


回答1:


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; }

and change the statement to

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

I imagine it should work.



来源:https://stackoverflow.com/questions/46112405/entity-framework-core-multiple-relationships-between-users-and-organizations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!