简体   繁体   中英

Entity Framework many to many, insert

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM