[英]SaveChanges throws System.Data.Entity.Core.EntityException
I'm having an issue trying to update the AspNetUsers database in MVC 5 with ASP.NET. 我在尝试使用ASP.NET更新MVC 5中的AspNetUsers数据库时遇到问题。
I'm trying to change a value in the user, Credits, which is stored in the database defined as Models.UserDB2.AspNetUsers
. 我正在尝试更改用户Credits中的值,该值存储在定义为
Models.UserDB2.AspNetUsers
的数据库中。
However, when I attempt this, I get thrown this error. 但是,当我尝试这样做时,会抛出此错误。
A first chance exception of type 'System.Data.Entity.Core.EntityException' occurred in EntityFramework.SqlServer.dll FATAL ERROR: An error occurred while starting a transaction on the provider connection.
EntityFramework.SqlServer.dll中发生了类型为'System.Data.Entity.Core.EntityException'的第一次机会异常致命错误:在提供程序连接上启动事务时发生错误。 See the inner exception for details.`
有关详细信息,请参见内部异常。
Inner exception: 内部例外:
A first chance exception of type 'System.Data.Entity.Core.EntityException' occurred in EntityFramework.SqlServer.dll is the inner exception
发生在EntityFramework.SqlServer.dll中的类型为'System.Data.Entity.Core.EntityException'的第一次机会异常是内部异常
This is the code causing the error. 这是导致错误的代码。
if(player != null) {
foreach(Models.Item item in itemDB.Items) {
if(item.UserAssetOptionId == id) {
if(!item.Owner.ToLower().Equals(username.ToLower())) {
return Content("false");
} else {
item.Owner = "HomeguardDev";
item.InMarket = true;
player.Credits += item.Value / 10;
try {
itemDB.SaveChanges();
userDB2.SaveChanges();
return Content("true");
} catch(Exception e) {
Debug.WriteLine("FATAL ERROR: " + e.Message);
return Content("false");
}
}
}
}
}
The database updates fine if I only update the itemDB
database, but I need to update the Credits value as well! 如果我仅更新
itemDB
数据库,则数据库更新良好,但是我还需要更新Credits值!
The model is updated with the latest schema with the database, so no problems there. 该模型将使用数据库的最新架构进行更新,因此在那里没有问题。
Anyone know what's up? 有人知道怎么回事吗?
The problem is that you're trying to save the changes to itemDB
while you're still iterating itemDB.Items
, try to change your code to: 问题是,您仍在迭代
itemDB.Items
时尝试将更改保存到itemDB
,请尝试将代码更改为:
if (player != null) {
foreach(Models.Item item in itemDB.Items) {
if (item.UserAssetOptionId == id) {
if (!item.Owner.ToLower().Equals(username.ToLower())) {
return Content("false");
} else {
item.Owner = "HomeguardDev";
item.InMarket = true;
player.Credits += item.Value / 10;
break;
}
}
}
try {
itemDB.SaveChanges();
userDB2.SaveChanges();
return Content("true");
} catch (Exception e) {
Debug.WriteLine("FATAL ERROR: " + e.Message);
return Content("false");
}
}
As long as you're in the foreach
, you can't start a second transaction. 只要您处于
foreach
,就无法开始第二笔交易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.