简体   繁体   中英

Entity Framework Code First - Relation

I am searching for the best way to do the next relation.

I have 2 entities, User and PartnerUser

public class User
{
    public int IdUser { get; set; }
    public string UserName { get; set; }
    public bool Validate { get; set; }        
}

public class PartnerUser
{
    public int IdPartnerUser { get; set; }        
    public int UserID { get; set; }
}

One user can have many partners (one to many) and Partner only can have one user but at the same time the Partner is an User (and this is my problem)

In Entity Framework what is the best way to create this relation?

As far as I understand, you don't have two entities here, only one - User . You can do a self-join as a one-to-many non-required relationship, so a User can have a Partner (many-to-one side) or Partners (one-to-many side):

public class User
{
    // I changed this to UserId to keep with naming conventions, 
    // it should otherwise be just Id, but not IdUser
    public int UserId { get; set; } 
    public int? PartnerId { get; set; }

    public User Partner { get; set; }
    public ICollection<User> Partners { get; set; }
}

You acpecting something like this...

public class User
{      
  public int IdUser { get; set; }

  public string UserName { get; set; }

  public bool Validate { get; set; } 

  public int? PartnerId { get; set; }

  public User Partner { get; set; }

  public ICollection<User> PartnerUsers{ get; set;}       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM