未在数据库中创建的模型的字符串集合属性

时间:2013-03-17 18:29:10

标签: c# entity-framework code-first

我创建了一个名为Tag的课程。

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

    public string Name { get; set; }

    public virtual ICollection<string> Synonyms { get; set; }
}

如何将Synonyms属性导入数据库?

我是否必须为它创建模型?

2 个答案:

答案 0 :(得分:1)

是的,你必须创建一个Model,或许这样做:

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

    public string Name { get; set; }

    public virtual ICollection<Synonym> Synonyms { get; set; }
}

然后你的同义词模型:

public class Synonym
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [HiddenInput(DisplayValue = false)]
    public int SynonymId { get; set; }

    [ForeignKey("Tag"), DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int TagId { get; set; }

    public string Name { get; set; }

    public virtual Tag Tag { get; set; }
}

答案 1 :(得分:1)

您必须将其包装在实体类

e.g。

public class Synonym
{
  int SynonymId {get; set;}
  string Synonym {get; set;}
}

或将您的收藏展平为单独的字符串字段

e.g:

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

    public string Name { get; set; }
    public string SynStore {get; set;}
    public IEnumerable<string> Synonyms 
{
    set { SynStore = String.Join(',', value);}
    get{ return SynStore.split(','); }
}
}