简体   繁体   English

实体框架多对多,插入

[英]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? 我的问题是如何向News对象添加Comment对象,以及如何更新和删除News Comment

Here is the News class: 这是News类:

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. 就个人而言,我将调整您的模型以取消NewsComment实体。 Your News entity would have a many-to-many property Comments , and the relation table would be handled internally. 您的News实体将具有多对多属性Comments ,并且关系表将在内部处理。 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: 编辑:要删除当前模型的注释,请将其从collection属性中删除:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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