Home > OS >  How to design Comment table that can reference either Question table or Answer table?
How to design Comment table that can reference either Question table or Answer table?

Time:06-18

For illustration purposes, let's consider 3 tables: Question, Answer and Comment with the following ORM models (in C#).

  • A question can have zero or more answers and/or comments.
  • An answer belongs to a question and can have zero or more comments.
  • A comment belongs to either a question or an answer.

The rules mimic SO/SE mechanism.

class Question 
{
  public int Id {get; set;}
  public string Content {get; set;}
  public IEnumerable<Answer> Answers {get; set;}
  public IEnumerable<Comment> Comments {get; set;}
}
class Answer
{
  public int Id {get; set;}
  public string Content {get; set;}
  public Question Question {get; set;}
  public IEnumerable<Comment> Comments {get; set;}
}
class Comment
{
  public int Id {get; set;}
  public string Content {get; set;}
  public ?????? For {get; set;}
}

Question

I have no idea how to construct the Comment table in which the property For can be either Question or Answer. What is the type of For property?

CodePudding user response:

nothing! leave it to EF, it will manage these relations. as a note, I can say the relations are one-to-many each Answer and Question has own Comment so if you want to put foreign keys you must use two keys for both of them

  • Related