[英]Entity framework core The instance of entity type cannot be tracked because another instance with the same key value
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}异常{“无法跟踪实体类型'BorrowToolFactor'的实例,因为已经在跟踪具有与{'BorrowToolFactorId'}相同键值的另一个实例。附加现有实体时,请确保只有一个具有给定键值的实体实例附加。考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。”} 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);此行发生错误: 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);我使用此代码而不是context.BorrowTools.AddRange(borrowTools); and it worked.它奏效了。 I don't know why context.BorrowTools.AddRange(borrowTools);我不知道为什么context.BorrowTools.AddRange(borrowTools); not worked.没用。
borrowTools.ForEach(_borrow => {
context.Entry(_borrow).State = Microsoft.EntityFrameworkCore.EntityState.Added;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.