1

Example

Let's say the number of answers of multiple choice questions varies. One question can have only 2 choices while another can have 10 choices.

How can I save these multiple choice questions in my SQL Server database? Is the following model viable?

public class MultipleChoiceQuestion
{
    [Key]
    public Guid Id { get; set; }

    [Required]
    public string Question { get; set; }

    // Suppose I can have 2-10 answers
    [Required]
    public List<string> Answers { get; set; }
}

Question

  • Can we store a list of objects with various length in a SQL Server database with code-first migration enabled in ASP.NET?
  • If it is not applicable, what is the best solution to deal with such problems?

1 Answer 1

2

You could create another object of type PossibleAnswer that would represent each individual answer for any particular multiple choice question. Then you would modify your Answers property in your MultipleChoiceQuestion object to be of type List. PossibleAnswer could be defined as follows:

 public class PossibleAnswer {
      public Guid Id {get;set;}
      public Guid MultipleChoiceQuestionId {get;set;}
      public string Answer {get;set;}
 }
Sign up to request clarification or add additional context in comments.

8 Comments

I agree, from a normalization standpoint this represents a one to many relationship, which calls for a separate table and required foreign key.
Got it. But from a technical point of view, is the MultipleChoiceQuestion model in my question compilable?
Oh, do you mean I can have List<PossibleAnswer>? Does it imply the database can store lists of objects?
No, basically with the model specified you would have one table, MultipleChoiceQuestion(s) and another table, PossibleAnswer(s) that would contain the 1 to many relationship between Questions and Answers
What happens if I execute select * from MultipleChoiceQuestion? What will be returned in the field List<PossibleAnswer>?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.