Reputation: 253
This is how my entities look like:
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
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