asp.net mvc 4 one to many relationship (article - tags)

為{幸葍}努か 提交于 2019-12-06 15:16:20

问题


I am trying to create 1-M relationship (1-*) and I cannot make this work.

I have Article model and ArticleTag model. Logically I want to have an article linked with many tags. In "non-model" way, I would make 2 tables according these two models.

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<ArticleTag> ArticleTags { get; set; }
}

public class ArticleTag
{
    public int ArticleID { get; set; } //FK of the Article
    public string TagName { get; set; }
}

I have seen only entities with an ID, but here, I wouldn´t think it´s necessary, to every row in ArticleTag table have its own ID. Isn´t it?

How should I write it down? Thx a lot.


回答1:


First of all, you need to have a unique Id for both ArticleTag and Article. Then you need to insert ArticleID into Article Tag, because the entity needs to know which ArticleTags belong to an Article. Simplified, this is how it should look:

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


来源:https://stackoverflow.com/questions/16927018/asp-net-mvc-4-one-to-many-relationship-article-tags

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