Serhii
Serhii

Reputation: 439

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

Upvotes: 1

Views: 44

Answers (1)

Backs
Backs

Reputation: 24913

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

Upvotes: 1

Related Questions