实体框架SaveChanges检测到关系角色的冲突变化

时间:2014-09-15 12:10:19

标签: c# entity-framework-6

我有这段代码:

public class Taxi
{
     [DataMember]
     public int Id { get; set; }         

     [DataMember]
     public string CarModel { get; set; }         

     [IgnoreDataMember]
     public virtual ICollection<Order> Orders { get; set; }       
}

public class Order
{
     [DataMember]
     public int Id { get; set; }

     [DataMember]
     public string AddressFrom { get; set; }

     [DataMember]
     public int? TaxisId { get; set; }

    [IgnoreDataMember]
     public virtual Taxi Taxi { get; set; }
}

............

public void SomeMethod(int orderId)
{
   using (var db = new MyDbContext())
   {
      var order = db.Orders.FirstOrDefault(x=>x.Id==orderId);
      if (order!=null) //order.TaxisId = 1
      {
        order.TaxisId = null;
        db.SaveChanges(); //everything Ok! order.TaxisId becomes null
        if (SettingsModel.AutoSetToTheNextTaxi)
        {
          OrderSetTaxis(order.Id, 2, db); //trying to set order.TaxisId to another value.
        }
        ......
        //Some Code
        ......
      }
   }
}

public void OrderSetTaxis(int orderId, int taxiId, MyDbContext db)
{
  var order = db.Orders.FirstOrDefault(x=>x.Id==orderId);
  if (order!=null)
  {
    order.TaxisId = taxiId;
    db.SaveChanges(); //this throw exception
  }
}

当我调用方法时,我有这个例外 - “已经检测到关系'DispKernel.Entities.MyDbContext.Order_Taxi'的角色'Order_Taxi_Target'的更改。” 我做错了什么?

1 个答案:

答案 0 :(得分:1)

问题是由于您同时在上下文中对同一实体进行了2次冲突更改,因此无法跟踪这些更改。然而,进行这两项修改毫无意义,只需执行以下操作即可:

public void SomeMethod(int orderId)
{
   using (var db = new MyDbContext())
   {
      var order = db.Orders.FirstOrDefault(x=>x.Id==orderId);
      if (order!=null) //order.TaxisId = 1
      {        
        if (SettingsModel.AutoSetToTheNextTaxi)
        {
          order.TaxisId = 2;
        }
        else
        {
          order.TaxisId = null;
        }
        db.SaveChanges(); 
      }
   }
}