[英]Entity Framework many to many, insert
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.