实体框架C#SaveChanges不会立即生效

时间:2018-11-17 11:57:47

标签: c# entity-framework

为什么在同一using语句上使用另一个DBContext.SaveChanges()DbContext不能立即生效?

例如:

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();
    }
}

1 个答案:

答案 0 :(得分:1)

如果我对您的理解正确;这应该有效..但不适用于第一个上下文中的提取实体。让我解释一下。

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();
    }
}

实体框架具有一个更改跟踪器,以跟上在获取的实体中所做的所有更改。此变更跟踪器位于上下文中。因此,不同的上下文具有不同的变更跟踪器,这些跟踪器彼此之间(并不是真正地)相互了解。