实体框架不保存对表所做的所有更改

时间:2016-08-01 11:33:40

标签: c# entity-framework savechanges

我试图在一种方法中将数据保存到两个不同的表中。第一次db.SaveChanges()调用会正确更新数据,但第二次调用SaveChanges时,即使我明确更改了数据,也无法执行任何操作。

PhaseStatus truckPhase = db.PhaseStatus.Where(x => x.TruckId == truckId).FirstOrDefault();
RTrucks truck = db.RTrucks.Where(x => x.Id == truckId).FirstOrDefault();

using (var ContextTransaction = db.Database.BeginTransaction())
{
    db.PhaseStatus.Attach(truckPhase);
    var entryPS = db.Entry(truckPhase);
    entryPS.State = EntityState.Modified;
    db.SaveChanges(); //Success

    if (truckPhase.Phase.PhaseName == "Not Started")
        truck.Status = "Quoted";
    else truck.Status = "Active";

    db.RTrucks.Attach(truck);
    var entryRT = db.Entry(truck);
    entryPS.State = EntityState.Modified;
    db.SaveChanges(); //Fails with no errors
    ContextTransaction.Commit();
}

有谁知道为什么EF6会这样做?我做错了吗?

1 个答案:

答案 0 :(得分:3)

在你的第二次改变中:

entryPS.State = EntityState.Modified;

entryRT.State = EntityState.Modified;