I have a basic question about implementing a Entity code first one to many db. I have two models, Articles and Comments like this:
public class Article
{
public int Id { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
....
public class Comment
{
public int Id { get; set; }
public virtual Article CommentForArticle { get; set; }
public DateTime TimeStamp { get; set;
....
If I try to add the Comment to the Db (with the Comment.CommentForArticle containing the Article) The comment is added to the database but Article does not contain the Comment in it’s collection of comments.
But if I create a comment, and add it to the article everything works fine. I didn’t have to add the comment to the database, it is added automatically (I guess.)
I was having problem after problem trying to implement this (errors like: Multiplicity constraint violated) so my question is, am I doing this correct now and why do you have to do it this way, not adding the Comment to the Db but to the Article that contains the comment. And can you share any link that may help me to better understand how the Entity Framework works with one to many and many to many relationships.
Thanks,
Garrett
I would prefer to add new items to an owner’s collection if there is a “has” relationship. In your case,
ArticlehasComments, so I would add a new Comment to article.Comments.An “is” relationsip, other than inheritance, is also possible. Suppose you had
ArticleTypeentities and a propertyarticle.ArticleType. In this case, I would prefer to set the property. I would not even likeArticleTypeto have anArticlesnavigation property.In case of “pure” many-to-many (i.e. when the join table is not mapped as an entity type of its own) there is no other alternative than adding items to owner’s collections.
It is not clear why you had problem after problem. Is it because you mixed both approaches? (adding Comments to the db and adding the same comments to the article).
As for a reference: a great series of articles starts here. It focusses on more complex scenarios, but references to regular case are not hard to find.