Reputation: 1342
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.
Upvotes: 0
Views: 1727
Reputation: 2639
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; }
}
Upvotes: 3