Attaching an entity of type 'X' failed because another entity of the same type already has the same primary key value. error

asp.net asp.net-mvc entity-framework-6

Accepted Answer

The first three suggestions were ineffective. Following along with your side note was eventually what I was obliged to do in order to find a solution (at least I think that is what you were getting at). The problem was caused by the GameType and AppplicationUsers inclusions' attempts to generate new entities of their respective objects rather than searching the database and marking the data as updated. The revised controller code that got it functioning is shown below:

[HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit(EditMatchesViewModel match)
    {

        if (ModelState.IsValid)
        {
            var updatedMatch = db.Matches.Find(match.ID);
            updatedMatch.Date = match.Date;
            updatedMatch.AwayTeam = match.AwayTeam;
            updatedMatch.HomeTeam = match.HomeTeam;
            updatedMatch.Division = match.Division;
            updatedMatch.Games = new List<Game>();

            foreach (var game in match.Games)
            {
                if (game.ID > 0)
                {
                    var updatedGame = db.Games.Find(game.ID);
                    updatedGame.GameType = db.GameType.Find(game.GameType.ID);
                    updatedGame.AwayPlayer1 = db.Users.Find(game.AwayPlayer1.Id);
                    updatedGame.AwayPlayer2 = db.Users.Find(game.AwayPlayer2.Id);
                    updatedGame.HomePlayer1 = db.Users.Find(game.HomePlayer1.Id);
                    updatedGame.HomePlayer2 = db.Users.Find(game.HomePlayer2.Id);
                    updatedGame.AwayScore1 = game.AwayScore1;
                    updatedGame.AwayScore2 = game.AwayScore2;
                    updatedGame.HomeScore1 = game.HomeScore1;
                    updatedGame.HomeScore2 = game.HomeScore2;

                    updatedMatch.Games.Add(updatedGame);
                }
            }
            db.Matches.Attach(updatedMatch);
            db.Entry(updatedMatch).State = EntityState.Modified;
            await db.SaveChangesAsync();

            return RedirectToAction("Index");
        }
        return View(match);
    }
0
5/13/2018 8:26:46 PM

Popular Answer

This line has an issue because anotherMatch entity set is still active and loaded with the exact same main key asMatch When storing updates, you can only have one object in memory with the same primary key for the viewmodel in the POST method:

db.Entry(match).State = EntityState.Modified;

as an alternative to settingMatch Try utilising an entity state like thatAttach() approach before actingSaveChangesAsync() :

db.Matches.Attach(match);
await db.SaveChangesAsync();

Or useAsNoTracking() to stop using entity trackingMatch while retrieving data using the GET action method:

Match matchData = await db.Matches.AsNoTracking()
      .Where(m => m.ID == id)
      .Include(t => t.AwayTeam)
      .Include(t2 => t2.HomeTeam)
      .Include(x => x.Games.Select(g => g.GameType))           
      .FirstOrDefaultAsync();

If the two aforementioned potential fixes don't work, setMatch object state toEntityState.Detached after a received query's GET action method:

if (matchData != null)
{
    context.Entry(matchData).State = EntityState.Detached;
}

In addition, it's preferable to loadMatch using the POST action method and the entity's main key (withFind() Instead of distancing and reattaching it, you might use a method to change property values or base them on an existing object stored in memory.

Similar problems

Due to an existing entity of the same type with the same primary key value, attaching an entity of type "MODELNAME" in ASP.NET MVC failed.

Attempting to save a change results in an error attaching entity due to the same primary key.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow