当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - IList<string> datatype field not being incorporated into table definition asp.net MVC

问题描述:

I have the following model class:-

public class EventReg

{

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]

public int ID { get; set; }

[Display(Name = "Event Date")]

[DataType(DataType.Date)]

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]

public DateTime? EventDate { get; set; }

[Display(Name = "Event Time")]

[DataType(DataType.Time)]

[DisplayFormat(DataFormatString = "{0:t}", ApplyFormatInEditMode = true)]

public DateTime? EventTime { get; set; }

public IList<string> HashTags { get; set; }

public string Category { get; set; }

[Display(Name = "Registered by")]

public string UniqueId { get; set; }

public float Latitude { get; set; }

public float Longitude { get; set; }

public string Description { get; set; }

}

In my Package-Manager-Console I typed Enable-Migrations -ContextTypeName CampusConnect.Models.EventDBContext(EventDBContext is my database ) to create a configuration.cs file. I didn't add any data into the seed method. then I did add-migration initial to create an intial.cs file which would allow my project to update my database schema. Now when I did update-database each field appeared in the table definition except the HashTag field. Can anyone tell me, why?

网友答案:

Because of HashTags property if of type IList - entity framework can't figure out how to declare it in database. So you need to help it. Basically you have two choices:

a) Make your field of string type and form it in your format (for example comma-separated string), then make additional property that will convert it to IList<string>:

public string HashTags { get; set; }
public string IList<string> HashTagsFormated 
{
    get {
       return { HashTags.Split(',').ToList(); 
    }
}

b) Make separate table for hash tags and link it to your EventReg table.

public class EventReg
{
   public EventReg()
   {
       HashTags = new HashSet<HashTag>();
   }
   //...your other fields
   public virtual ICollection<HashTag> HashTags { get; set; }
}

public class HashTag
{
    [Key]
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int HashTagID {get;set;}

    public string HashTagName {get;set;}
    public virtual EventReg EventReg { get; set; }
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: