Entity with multiple members of the same type in the Entity Framework

5

When we have two many-to-many related entities and create the navigation properties correctly, the entity creates an extra table to set up this relationship.

In the case where I'm working I have a structure that in the best of worlds would look like this:

public class User {
    public string Name {get;set}
    public int id
}

public class Forum {
    public string Title {get;set}
    public virtual ICollection<User> Participants {get;set}
    public virtual ICollection<User> Followers {get;set}
}

The problem here is precisely because it has two properties of type User. The entity will try to save everything in the same table, and will create two foreign keys in User.

What is good practice in this case? Would you create two different entities (Participants and Followers) and store the User and Forum ids in each of them?

    
asked by anonymous 18.12.2015 / 08:25

1 answer

3
  

What is good practice in this case?

It depends on what you need. If you need the data to be unified, the approach is correct. If this is not necessary, it is appropriate to separate.

In case of a unified structure, upgrade to the following:

public class User 
{
    public int id
    public int? ForumParticipantId { get; set; }
    public int? ForumFollowerId { get; set; }
    public string Name { get; set; }

    public virtual Forum ForumParticipant { get; set; }
    public virtual Forum ForumFollower { get; set; }
}

public class Forum 
{
    public int id { get; set; }
    public string Title { get; set; }

    [InverseProperty("ForumParticipant")]
    public virtual ICollection<User> Participants { get; set; }
    [InverseProperty("ForumFollower")]
    public virtual ICollection<User> Followers { get; set; }
}

Learn more about [InverseProperty] here .

    
18.12.2015 / 16:27