简体   繁体   English

(EF)在插入新实体时更新相关数据

[英](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. 我有PostsComments表, Comments通过postIdPosts相关,并且在插入新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();
  1. Select Post 选择Post
  2. Add new Comment in Post's Comments collection 在帖子的Comments集合中添加新Comment
  3. Change date 改变日期
  4. Save Changes. 保存更改。 EF will generate two statements: insert and update EF将生成两个语句:insert和update

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.

相关问题 在 EF Core 中为实体添加数据期间更新相关实体数据 - Update related entities data during adding data for an entity in EF Core 如何正确更新(添加/更新/删除)实体的相关数据(EF Core) - How to properly update (add/update/remove) related data of entity (EF Core) 在 EF 中定义一个实体,在删除时保留相关数据 - Define an entity in EF that keeps related data on delete EF Core 插入具有现有子项的新实体 - EF Core insert new entity with existing children 如何更新EF中相关表中的数据? - How to update data in a related table in EF? 当我希望它更新时,实体正在尝试为相关表插入新记录 - Entity is trying to insert a new record for a related table when I want it to update EF-相关实体未加载 - EF - related entity not loading EF Core - 为新的未保存实体获取相关实体 - EF Core - Get related entities for a new unsaved entity 如何在 EF Core 3+ 中使用具有状态(修改、添加、删除)的请求/正文自定义对象更新具有相关数据(数组)的实体? - How to update an entity with related data (arrays) from request/body custom objects with states (modified, added, removed) in EF Core 3+? 在 EF Core 中添加新实体后如何更新实体 - How update entity after adding new entity in EF Core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM