Felipe Miosso
Felipe Miosso

Reputation: 7339

Two entities with common one-to-many relationship

I have the following scenario in my project and I'm starting to get with a few questions about it.

On the User class, querying QuestionFollows directly will be better (in terms of performance) than querying Questions and then QuestionFollows?

Another question ... is the relationship between User and QuestionFollow necessary/redudant?

Domain

public class User
{
    public long   UserID { get; set; }
    public string Name   { get; set; }

    public virtual ICollection<Question>       Questions       { get; set; }
    public virtual ICollection<QuestionFollow> QuestionFollows { get; set; }
}

public class Question
{
    public long   QuestionID  { get; set; }
    public long   UserID      { get; set; }
    public string Description { get; set; }
    public User   User        { get; set; }

    public virtual ICollection<QuestionFollow> QuestionFollows { get; set; }
}

public class QuestionFollow
{
    public long     QuestionFollowID { get; set; }
    public long     QuestionID       { get; set; }
    public long     UserID           { get; set; }
    public DateTime Date             { get; set; }
    public Question Question         { get; set; }
    public User     User             { get; set; }
}        

Upvotes: 0

Views: 66

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

Everything you're doing seems right based on assumptions I gather from your code: a user has questions and can also follow questions that belong to other users. If that's correct, then it seems you're simply struggling with how these relationships play out.

From User, querying Questions will return all questions belonging to that User instance. Querying QuestionFollows, however, will return all questions that User has chosen to follow, whether or not those questions belong to that User instance. In other words, these are two functionally different datasets, so it's not about which is more performant; it's about which returns the data you actually need.

The relationship between User and QuestionFollows is also not redundant, because again you're tracking a fundamentally different facet of the relationship. In QuestionFollow the User is the entity that is following the question and the Question is the entity that is being followed. That Question entity could have a completely different User attached to it, as that User entity is the one who owns the question.

Upvotes: 1

Related Questions