Storing list of objects in a SQL Server database with code-first

冷暖自知 提交于 2019-12-11 13:58:31

问题


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


来源:https://stackoverflow.com/questions/27296902/storing-list-of-objects-in-a-sql-server-database-with-code-first

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!