Waleed Halaby
Waleed Halaby

Reputation: 61

Entity Framework C# SaveChanges doesn't take effect immediately

Why DBContext.SaveChanges() doesn't take effect immediately when using another DbContext on the same using statement?

As an example:

public void ChangeStatus(int id)
{
    using(DBContext context = new DBContext())
    {
        var car = context.Cars.FirstOrDefault(x => x.id == id);
        car.status = 1;
        context.SaveChanges();
        UpdateAnotherStatus(id);
    }
}

public void UpdateAnotherStatus(int id)
{
    using(DBContext context = new DBContext())
    {
        var car = context.Cars.FirstOrDefault(x => x.id == id);
        car.status2 = 2;
        context.SaveChanges();
    }
}

Upvotes: 1

Views: 328

Answers (1)

Stefan
Stefan

Reputation: 17658

If I understand you correctly; this should work.... but not for the fetched entity in the first context. Let me explain.

public void ChangeStatus(int id){
    using(DBContext firstContext = new DBContext()){
        var firstCar = firstContext .Cars.FirstOrDefault(x=>x.id == id);
        firstCar .status = 1;
        context.SaveChanges();
        UpdateAnotherStatus(id);

        //at this point, the data set in the secondContext
        //did not update `firstCar` because they are completely seperate.
        //to overcome this eighter refetch (slow) or use the firstCar object or firstContext
        //to update status2
    }
}

public void UpdateAnotherStatus(int id){
    using(DBContext secondContext = new DBContext()){
        var secondCar = secondContext .Cars.FirstOrDefault(x=>x.id == id);
        secondCar .status2 = 2;
        secondContext .SaveChanges();
    }
}

Entity Framework has a change tracker to keep up with all the changes made in the fetched entities. This change tracker lives in the context. So different context has different change trackers, which are not (really) aware of each other.

Upvotes: 1

Related Questions