简体   繁体   中英

The instance of entity type Menu cannot be tracked

I started a new asp.net core project. As you know in Core version 2.1 has dependency injection.

I have a model called MenuModel to create a table in my database. I added an interface called IMenuRepository for my model and a class call MenuRepository that implements my Interface.

I try to edit my menu in my repository like this

    public async Task Edit(Menu menu)
    {
        menu.UpdatedBy = _userId;
        menu.UpdatedDate = DateTime.Now;

        _db.Entry(menu).State = EntityState.Modified;
        await _db.SaveChangesAsync();
    }

I added this line of code to my startup.cs for dependency injection

services.AddTransient<IMenuRepository, MenuRepository>();

I found another question that asked the same question and the answer says I have to change my startup.cs code like:

services.AddScoped<IMenuRepository, MenuRepository>();

I did and I tried the others as well but I get this error always. I searched a couple of times but I can't find any solution to my problem.

One time I detached my model from my DatabaseContext before editing and I got the same error as well.

I tried with this code to update but no result

_db.Update(menu);

Here is my error description:

**An unhandled exception occurred while processing the request.

InvalidOperationException: The instance of entity type 'Menu' cannot be tracked because another instance with the same key value for {'MenuId'} 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. Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap.ThrowIdentityConflict(InternalEntityEntry entry)**

On the other hand, I have a part of the code for publishing and unpublish menu that changes the record status and that edit the menu like this and it works perfectly.

    public async Task Publish(int id)
    {
        Menu menu = await Find(id);

        menu.UpdatedBy = _userId;
        menu.UpdatedDate = DateTime.Now;
        menu.Status = eStatus.Published;

        _db.Entry(menu).State = EntityState.Modified;
    }

The difference is only I send the menu id to publish method and send menu obj to edit.

After searching in different languages I found the answer to my question

I changed my edit method to this:

    public async Task Edit(Menu menu)
    {
        menu.UpdatedBy = _userId;
        menu.UpdatedDate = DateTime.Now;

        var editVersion = await Find(menu.MenuId);
        if (editVersion != null)
        {
            _db.Entry(editVersion).CurrentValues.SetValues(menu);
        }
        await _db.SaveChangesAsync();
    }

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