Suppose I have code which retrieves an object and modifies it and submits it via any ORM from a web application. Below is the pseudo code:
First request
var objCust = _dbContext.Customers.Where(c=>c.CustomerId == "ALFKI").SingleOrDefault();
objCust.Address ="test address 1";
//and add some orders
_dbContext.SubmitChanges();
Second simultaneous request
var objCategory = _dbContext.Categories.Where(c=>c.CategoryId == 1).SingleOrDefault();
objCategoryName = "test name";
_dbContext.SubmitChanges();
How does the first request only grasp the changes done to customers and submit the changes. Is there any mechanism inbuilt in ORM’s to track changes to entities per thread or request.
1
Most O/RMs are not thread-safe. When using an O/RM in a web app, the common practice is to create a UnitOfWork per request that is tied to that request’s thread. Another option is to expose the UnitOfWork as a [ThreadStatic] variable. And finally, there are some Dependency Injection containers that will allow you to tie the lifetime of an object (e.g. a UnitOfWork) to a thread.
The ORM does not (always) manage the transactionality. At the end of the day, the transactionality is going to be handled by the ACID guarantees of your database while the ORM simply acts as a communication layer with your database.
That said, some ORMs have built-in caching and other more complex techniques in attempts to avoid the database except when necessary to lower the load on the database. In these forms of ORMs there is surely transactionality management required to some extent, and the technique will be the same techniques any multi-threaded app uses for transaction handling: shared state with locks/semaphores/signals/mutexes where necessary inside of the ORM. Alternatively they could be lacking those locks and be simply not thread safe for certain scenarios, but I have to think an ORM developer is going to be knowledgeable enough to be keen on these scenarios and focus on ensuring thread safety.
Note I say this referring to the Java/C# style OO languages where locking is the required technique for multi-threaded safety assurances, I do recognize other types of languages use lockless techniques.
2
ORM is tracking changes per session object not per request/thread.
When I say session I mean _dbContext in your example.
In web applications it is common practice to create one session object per web request.
So if both requests are separate then none of _dbContexts knows about any other.
In your example there will be two updates sent to database.