The project is a .net core 7.0 web api using entity framework core and DI.
I have two instances of DbContext, one instance checks to see if the entity or record is created, if it isn't it calls a method in a class to create that record and pass the Id. Then it searches for the record again using the Id to update it.
I noticed that if the dbContext instance that creates the record wasn't disposed correctly, when I update properties in the second instance for the same record, it doesn't actually update it. It seems to be updating the other instance again (I think).
Due to dbContext having concurrency constraints, I specifically created two separate instances, to have this separation of concerns.
First class with dbContext that is injected via Dependency Injection
if (study is null)
{
var logMessage = $"Unable to find {StudyInstanceUid} in the database. Creating a new study and marking it as an exception.";
_logger.LogWarning(logMessage);
var studyId = await _cs.CreateStudy(myStudy);
study = await (from s in _cdb.Studies where s.Id == studyId select s).FirstAsync();
}
Service class that has the create methods
public async Task<int> CreateStudy(studyNotification record)
{
var _optionsBuilder = new DbContextOptionsBuilder<MyDbContext>();
_optionsBuilder.UseSqlServer(_config.GetConnectionString("MyDb"));
using var _cdb = new MyDbContext(_optionsBuilder.Options);
var study = new Study()
{
...
};
_cdb.Studies.Add(study);
await _cdb.SaveChangesAsync();
return study.Id;
}
If I modify the code above to:
await _cdb.SaveChangesAsync();
int id = study.Id;
return id;
It works as expected. While I do not understand the inner workings of entity framework core, I would have thought that the two different instances would not interfere with each other. I would like to understand why this issue occurs?