简体   繁体   中英

SaveChanges throws System.Data.Entity.Core.EntityException

I'm having an issue trying to update the AspNetUsers database in MVC 5 with ASP.NET.

I'm trying to change a value in the user, Credits, which is stored in the database defined as 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. 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

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!

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:

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM