简体   繁体   中英

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM