Storing list of objects in a SQL Server database w

2019-07-27 17:11发布

问题:

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:

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;}
 }