entity framework SaveChanges conflicting changes to the role of the relationship have been detected

c# entity-framework-6

Question

I have this code:

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
  }
}

When i calling method I have this exception - "Conflicting changes to the role 'Order_Taxi_Target' of the relationship 'DispKernel.Entities.MyDbContext.Order_Taxi' have been detected." What am I doing wrong?

1
1
9/15/2014 1:07:53 PM

Accepted Answer

The problem is caused by the fact that you have 2 conflicting changes to the same entity in the context at the same time, so it cannot track these changes. However there is no point in ever making both changes so simply do the following:

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(); 
      }
   }
}
1
9/15/2014 1:11:25 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow