Search code examples
asp.net-mvccode-first

How to have a list or an array of string in my model of ASP.NET MVC_CodeFirst


I want to use Code-first Database.This is my Model of asp MVC

Model:

public class Question
{
    public virtual int Id { get; set; }
    public virtual string Qu { get; set; }
    public virtual string Ans { get; set; }
    public virtual List<string> KeyWords { get; set; }
}

Each object of Question must have a list of KeyWords. Is it a correct way or it will be better if I have a model of KeyWords then here create a list of object keyword?

Appreciate your help, thanks!


Solution

  • I would think if you want to store the data in a database you would need to normalize the code. I would do it this way:

    public class Question
    {
        public int Id { get; set; }
        public string Qu { get; set; }
        public string Ans { get; set; }
        public virtual List<string> KeyWords { get; set; }
     }
    public class Keyword
     {
        public int Id {get;set;}
        [ForeignKey("question")]
        public int QuestionID {get;set;}
        public string keyword {get;set;}
        public virtual Question question {get;set;}
     }
    public QuestionModel :DBContext
     {
        public virtual DBSet<Question> Questions {get;set;}
        public virtual DBSEt<Keywords> Keyword {get;set:}
     }
    

    I use ICollection<> instead of List for the virtual collections but I'm not sure it matters.