Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-core/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尝试执行存储过程时发生实例冲突错误_C#_Asp.net Core_Entity Framework Core_Asp.net Core 3.1 - Fatal编程技术网

C# 尝试执行存储过程时发生实例冲突错误

C# 尝试执行存储过程时发生实例冲突错误,c#,asp.net-core,entity-framework-core,asp.net-core-3.1,C#,Asp.net Core,Entity Framework Core,Asp.net Core 3.1,我有以下PUT方法,用于通过.NET Core&Entity Framework更新我的现金列表表中的对象 我必须向SQL Server数据库中的存储过程添加一个调用 如果正在更新的对象的某个属性发生更改(CashCountry),则调用该函数 [HttpPut(“{id}”)] 公共异步任务PutCashList(字符串id,CashList CashList) { var newCashCountry=cashList.CashCountry; var currentCashObject=w

我有以下PUT方法,用于通过.NET Core&Entity Framework更新我的现金列表表中的对象

我必须向SQL Server数据库中的存储过程添加一个调用

如果正在更新的对象的某个属性发生更改(
CashCountry
),则调用该函数

[HttpPut(“{id}”)]
公共异步任务PutCashList(字符串id,CashList CashList)
{
var newCashCountry=cashList.CashCountry;
var currentCashObject=wait_context.CashList.FindAsync(id);
var currentCashCountry=currentCashObject.CashCountry;
if(newCashCountry.Value!=currentCashCountry)
{
wait_context.Database.executeSqlRawaAsync(“EXEC bank_UpdateCash{0},{1}”、cashList.CashId、cashList.CashCountry);
}
_context.Entry(cashList.State=EntityState.Modified;
wait_context.SaveChangesAsync();
返回NoContent();
}
但每当我测试它时,就会出现以下错误:

System.InvalidOperationException:无法跟踪实体类型“CashList”的实例,因为已在跟踪另一个具有{CashId'}相同键值的实例

我不知道为什么,因为我只想更新一行

任何线索都欢迎


谢谢

这是由这两条线引起的:

var currentCashObject = await _context.CashList.FindAsync(id);
 _context.Entry(cashList).State = EntityState.Modified;
我假设id属于
cashList
参数。因此,第一行生成实体框架跟踪的
CashList
对象。因此,第二行也尝试这样做。 您可以将第一行更改为:

var currentCashObject = await _context.CashList.AsNoTracking().FindAsync(id);

告诉实体框架不要跟踪从db获得的对象。

这就是您的全部代码吗?或者为了简洁起见,它有一些剥离的部分?尝试在项目中添加DbContext作为作用域服务依赖项?@svyatis.lviv谢谢!我在Startup.cs文件中有
services.AddDbContext
,并将其注入每个控制器。我还需要什么吗?@Eldar是的,先生,我确实取出了一个长的
try-catch
块,如果出现空值,它会写入错误日志。但在这种情况下,没有什么是无效的。
var currentCashObject = await _context.CashList.AsNoTracking().FindAsync(id);