简体   繁体   中英

(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.

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();
  1. Select Post
  2. Add new Comment in Post's Comments collection
  3. Change date
  4. Save Changes. EF will generate two statements: insert and update

Like this:

var post = context.Posts.FirstOrDefault(...);
post.Comments.Add(comment);
post.DateUpdated = DateTime.Now;
context.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