ASP.Net MVC Error: Attaching an entity of type failed because another entity of the same type already has the same primary key value

mukesh1
 
on Jul 24, 2018 12:35 AM
16017 Views

System.InvalidOperationException: 'Attaching an entity of type 'leisure.Models.Sale' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.'

Actually i m updating my table data according to other model.

Sale sal = new Sale();
var order = db.Sales.Where(s => s.Bill_Id == _Leisure.Order_id)
            .FirstOrDefault();
sal.Customer_Name = order.Customer_Name;
sal.Payment_Type = "2";
sal.Org_id = order.Org_id;
sal.Staus = "Pending";
sal.Bill_Id = _Leisure.Order_id;
db.Entry(sal).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
mukesh1
 
on Jul 24, 2018 01:34 AM

 

var order = db.Sales.AsNoTracking().Where(s => s.Bill_Id == _Leisure.Order_id)
                               .FirstOrDefault();

Problem solved by use of AsNoTracking()