asp.net mvc 4一对多的关系(文章 – 标签)

我正在尝试创建1-M关系(1- *),但我无法完成这项工作。

我有文章模型和ArticleTag模型。 从逻辑上讲,我想要一篇与许多标签相关联的文章。 在“非模型”的方式,我会根据这两个模型制作2个表。

public class Article { public int ArticleID { get; set; } public string Title { get; set; } public DateTime Date { get; set; } public string Anotation { get; set; } public string Body { get; set; } public string SourceLink { get; set; } public virtual ICollection ArticleTags { get; set; } } public class ArticleTag { public int ArticleID { get; set; } //FK of the Article public string TagName { get; set; } } 

我只看到有ID的实体,但在这里,我认为没必要,因为ArticleTag表中的每一行都有自己的ID。 不是吗?

我应该怎么写下来? 多谢。

首先,您需要为ArticleTag和Article提供唯一的ID。 然后,您需要将ArticleID插入Article Tag,因为实体需要知道哪些ArticleTag属于Article。 简化,它应该是这样的:

 public class Article { public int ArticleID { get; set; } public string Title { get; set; } public DateTime Date { get; set; } public string Anotation { get; set; } } public class ArticleTag { public int ArticleTagID { get; set; } public int ArticleID { get; set; } //This creates the link 1-M public string TagName { get; set; } }