Search code examples
entity-frameworkdatabase-designpoco

Entity Framework POCO Desgn - Sort a List according to user preferences


I have a question regarding database design: What is the best way to sort a List according to user preferences?

My classes looks like this:

public class Questionnaire
{
  public string Name {get; set;}

  public virtual ICollection<Question> {get; set;}
}

public class Question
{
  public string QuestionText {get; set;}

  public int Answer {get; set;}
}

The relationship is N:N - a questionaire can have many questions and a question can part of multiple Questionnaires. Example: Imagine a Questionnaire about Satisfaction with Stackoverflow, there might be a Question like "do you like the site overall?". The question then might be reused in a Questionnaire about Geocities.

My problem is, that the Questions should have an order - which has to be supplied when the Questionnaire is constructed. The order is not simply alphabetic, but fixed to fit the idea of the creator of the Questionnaire. (E.g.: You would like to ask some broad questions first, then dive into the details.) How can I best model this? It cannot be a property on the Question, because the order depends on the Questionnaire, not the question. Should I add a third class, which applies a "weight" to each Question?


Solution

  • You need an intermediate table as the order is potentially different per questionnaire. Remove the navigation from Questionnaire to Question and insert a table in the middle to link them:

    public class Questionnaire
    {
      public string Name {get; set;}
      public virtual ICollection<QuestionItem> QuestionItems {get; set;}
    }
    
    public class QuestionItem
    {
        public int Order { get; set; }
        public virtual Questionnaire Questionnaire { get; set; }
        public virtual Question Question { get; set; }
    }
    
    public class Question
    {
      public string QuestionText {get; set;}
      public int Answer {get; set;}
    }