In a single request, that is, within a thread, if you use the EF data context object to create one, it will cause data confusion, each time the object created by the corresponding database operation, while the other EF objects obtained in the data may already be "expired". That this data has been changed. This is the data chaos, in order to solve this problem, the key is the object creation problem.
The first thing to think about is a singleton pattern, but here, it's not a good idea, because using a singleton mode will cause the EF object to not be released in a timely manner.
The second way is to ensure that the object within the thread is unique, how to ensure that, through the Microsoft ASP mechanism of the HttpContext object, the object is unique in the thread, so we create in the HttpContext or say add an object, Add the EF data context object that we want to create to HttpContext.
How to add it, you can add this method to the tool class (Common.cs) to create a
if (Httpcontext.current.item[ "" Span style= "color: #800000;" >db ] = = null = // modelcontainer the name of the EF context object that was created, model is the name of the entity model, and its own named Httpcontext.currentitems[ "] = DB1; // EF data context object added to HttpContext Span style= "color: #000000;" >} else { // Description has been added to HttpContext }
Unique within the thread created by the EF context object