[英](EF) Update related data on insert new entity
I have Posts
and Comments
tables, Comments
are related to Posts
by postId
, and I need to change DateUpdated
field in Posts
table when inserting new Comment
entity. 我有
Posts
和Comments
表, Comments
通过postId
与Posts
相关,并且在插入新Comment
实体时需要更改Posts
表中的DateUpdated
字段。
Is there any way to do this with one query and how to do it properly if it is not? 有没有办法对一个查询执行此操作,如果没有,如何正确执行?
Now I`m doing this way: 现在我正在这样做:
context.Comments.Add(comment);
context.SaveChanges();
context.Posts
.Single(p => p.Comments.Contains(c => comment.Id)
.DateUpdated = DateTime.Now;
context.SaveChanges();
Post
Post
Comment
in Post's Comments
collection Comments
集合中添加新Comment
Like this: 像这样:
var post = context.Posts.FirstOrDefault(...);
post.Comments.Add(comment);
post.DateUpdated = DateTime.Now;
context.SaveChanges();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.