I am using entity framework 6, in a C# application.
I have the following logic
using (var context = new MyContext())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
// Do LogicA
// Insert a new user to the database
context.SaveChanges();
// Take the inserted userID.
// Do LogicB
context.SaveChanges();
dbContextTransaction.Commit();
return user;
}
catch (Exception)
{
dbContextTransaction.Rollback();
return null;
}
}
}
Basically I am inserting a user to the database in LogicA, and I will need his ID (from the database, after the insert) in order to proceed with logicB. That's why I am doing 2 save changes. The first one in order to get the userID.
I added a Transaction, because sometimes, LogicB might throw an exception, and if that happens, I want to rollback the changes done (remove the user from the db)
That logic is working correctly, however I have a question:
Lets say 2 requests has been made at the same time, and this specific scenario happens:
Request 1 and Request 2 arrive at the same exact time
Scenario:
Request 1 Do LogicA, Insert user1 and save changes
Request 2 Do LogicA, Insert user2 and save changes
Request 1 Get Id for user1, Do LogicB, exception happens, Rollback the changes by removing user1, returns null
Request 2 Get Id for user2, Do LogicB, LogicB does NOT throw an exception, all is fine, returns user2
Since it is very hard to reproduce this scenarion, I want to ask about something that is worrying me:
Finally, the question :)
If the request to insert user 1 fails, but user 2 succeed, Would the database ID of user2 change? (because user1 got deleted when I rolled back) did user 2 change his ID to adapt to the rollback that happened in the other request, or did he remain the same ID that was assigned at first? (His database ID I mean)
I hope I was clear Thanks for any clarifications,