I have a method to update a Factor, but when I execute method it not work.
this is error:
exception {"The instance of entity type 'BorrowToolFactor' cannot be tracked because another instance with the same key value for {'BorrowToolFactorId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values."} System.Exception {System.InvalidOperationException}
public static long Save(BorrowToolFactor borrowToolFactor, List<BorrowTool> borrowTools)
{
CheckQueryResult.ResultError = string.Empty;
long _result = 0;
using (var context = new StoreManagerContext())
{
try
{
_result = orginalBorrowToolFactor.BorrowToolFactorId;
context.Entry(orginalBorrowToolFactor).CurrentValues.SetValues(borrowToolFactor);
#region DeleteOriginalBorrowTool
var originalBorrowTool = context.BorrowTools.Where(_borrow => _borrow.BorrowToolFactorId == _result).ToList();
context.BorrowTools.RemoveRange(originalBorrowTool);
#endregion DeleteOriginalBorrowTool
#region AddNewBorrowTools
borrowTools.ForEach(_borrow => _borrow.BorrowToolFactorId = _result);
context.BorrowTools.AddRange(borrowTools);
#endregion AddNewBorrowTools
}
context.SaveChanges();
}
catch (Exception exception)
{
_result = 0;
CheckQueryResult.ResultError = "Error: " + exception.Message;
}
return _result;
}
}
error happen on this line: context.BorrowTools.AddRange(borrowTools);
I use same method for another table worked correctly but this method not working.
I use this code instead of context.BorrowTools.AddRange(borrowTools); and it worked. I don't know why context.BorrowTools.AddRange(borrowTools); not worked.
borrowTools.ForEach(_borrow => {
context.Entry(_borrow).State = Microsoft.EntityFrameworkCore.EntityState.Added;
});
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.