Lucy
Lucy

Reputation: 253

Entity Framework many to many, insert

This is how my entities look like:

enter image description here

My question is how to add Comment object to News object and how to update and delete Comment of news?

Here is the News class:

News news = db.News.SingleOrDefault(n => n.NewsId == Id);

Upvotes: 0

Views: 2108

Answers (1)

Mr Anderson
Mr Anderson

Reputation: 2233

As your model stands now, you can do it like this:

News news = db.News.SingleOrDefault(n => n.NewsId == Id);
Comment comment = new Comment { Body = "This is my comment" };
NewsComment newsComment = new NewsComment { News = news, Comment = comment };
news.NewsComments.Add(newsComment);
db.SaveChanges();

Personally, I would adjust your model to take away the NewsComment entity. Your News entity would have a many-to-many property Comments, and the relation table would be handled internally. Your code would then become:

News news = db.News.SingleOrDefault(n => n.NewsId == Id);
Comment comment = new Comment { Body = "This is my comment" };
news.Comments.Add(comment);
db.SaveChanges();

Edit: To delete a comment with your current model, remove it from the collection property:

News news = db.News.SingleOrDefault(n => n.NewsId == Id);
NewsComment commentIDontWant = news.NewsComments.First(nc => nc.Comment.Body == "Bad Comment");
news.NewsComments.Remove(commentIDontWant);
db.SaveChanges();

Upvotes: 3

Related Questions