Quantcast
Channel: ADO.NET, Entity Framework, LINQ to SQL, NHibernate
Viewing all articles
Browse latest Browse all 1698

[EF Core / DbContext] If I .Add() a row in a seperate thread, related tables/rows' state are set to EntityState.Added => Exception

$
0
0

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? 


Viewing all articles
Browse latest Browse all 1698

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>