dotnet / efcore

EF Core is a modern object-database mapper for .NET. It supports LINQ queries, change tracking, updates, and schema migrations.
https://docs.microsoft.com/ef/
MIT License
13.82k stars 3.2k forks source link

Use Same DBContext instance get record from DataBase multiple times ,always the same result #16457

Closed WangFeng2333 closed 2 years ago

WangFeng2333 commented 5 years ago

Dear guys,

I am facing an issue that we have an asp.net webapi core 2.2 project with EF core 2.2. We are using default IOC framework to create the DBContext with Scope lifetime. And we have an Socket pipeline connect to our asp.net webapi service , I find that even we change the data by Web Front-end, the socket pipeline will always get the Old result( we are using FirstOrDefault to fetch the data ,it should not be the problem with first-level cache). So I infer , it might be because of that the Scope Lifetime DbContext , so I change it to Transient Lifetime . And it works! We get the modified record.

I have two questions:

  1. Is that behavior of DBContext by design? Or maybe I have some tricky issue in my code.
  2. how much performance effort will the Transient Lifetime DBContext cost?Since maybe I will make every DBContext Transient
ajcvickers commented 5 years ago

@WangFeng2333 A single DbContext instance is recommended for each unit-of-work. That is, the context instance should be constructed, the work performed, and then it should be disposed.

In a web-app, this context instance lasts for the lifetime of the request by registering it as Scoped in the container. However, registering as Transient is also a valid option if there isn't a natural request scope or if multiple independent units-of-work are needed.