Just to make it clear:
I use an injected instance of DbContext when it runs outside the thread, and a new DbContext() inside the thread.
Whether I run the code in a seperate thread or not, the ChangeTracker has Entries for the row I want to add, plus rows from all related tables.
The difference is that when I try to add a row in a seperate thread, all the related rows' EntityState are set to EntityState.Added:
db.VehicleWarehouse.Add(vehicleWarehouse);
entries = db.ChangeTracker.Entries();
cnt = entries.Count();
if (cnt > 1)
{
foreach (var entry in entries)
{
var entity = entry.Entity;
var state = entry.State;
if (entity != vehicleWarehouse)
{
// all related tables ends up in a seperate entity, up to the very top (VehicleWarehouse->Vehicle->Company)
// if the code is in a seperate thread, State is always set to Added => Exception
if (state == EntityState.Added)
db.Entry(entity).State = EntityState.Unchanged; // prevent insert exception
}
}
}
db.SaveChanges();
I start the thread like this:
Task.Run(() => {
FindVehicleWarehouse(vehicle, isLooking);
});What could be causing this, and is there a way to prevent it from happening?