简体   繁体   English

EF Core 上下文不包含添加实体的更改

[英]EF Core Context does not contain changes for added entities

I have .NET Core 3.1 Web API with EF Core 3.1.我有 .NET Core 3.1 Web API 和 EF Core 3.1。 I have DbContext with Scoped lifetime.我有带 Scoped 生命周期的 DbContext。

I have two services where I inject DbContext in the constructor.我有两个服务,我在构造函数中注入 DbContext。 When I update the existing entity in Service1 (and not call SaveChanges, just context.Update) then I can see an updated entity in context in Service2 (during one request of course).当我更新 Service1 中的现有实体(而不是调用 SaveChanges,仅调用 context.Update)时,我可以在 Service2 的上下文中看到一个更新的实体(当然是在一个请求期间)。

BUT

When I create a new entity in Service1 (and not call SaveChanges, just context.Add) then this entity is absent in context in Service2.当我在 Service1 中创建一个新实体(而不是调用 SaveChanges,只是调用 context.Add)时,该实体在 Service2 的上下文中不存在。

Why does it happen and is it possible to fix it to have added entities in any service where I inject context?为什么会发生这种情况,是否可以修复它以在我注入上下文的任何服务中添加实体?

When you issue a database query (without specifying the AsNoTracking option) , the context will throw away the loaded data for any entities it is already tracking, and return the existing instance instead.当您发出数据库查询(未指定AsNoTracking选项)时,上下文将丢弃它已经跟踪的任何实体的加载数据,并返回现有实例。 This is why your service is seeing the updated details for the entities which have not been saved.这就是为什么您的服务会看到尚未保存的实体的更新详细信息。

However, since the database query won't return any details for the entities which have been added but not yet saved, they will not be included in the results of the query.但是,由于数据库查询不会返回已添加但尚未保存的实体的任何详细信息,因此它们不会包含在查询结果中。

If you want to see the pending changes, you would need to query the DbSet<TEntity>.Local collection instead.如果要查看挂起的更改,则需要改为查询DbSet<TEntity>.Local集合

Change Tracking in EF Core EF Core 中的更改跟踪

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM