Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Asp.net Core EF Update

$
0
0

Hi all,

I follow Building Your First Web API with ASP.NET Core MVC and Visual Studio, but I got error below at _context.TodoItems.Update(item);

An exception of type 'System.InvalidOperationException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code

Additional information: The instance of entity type 'TodoItem' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.

Here is my code:

public class TodoRepository : ITodoRepository
{
    private readonly TodoContext _context;

    public TodoRepository(TodoContext context)
    {
        _context = context;
        //initialize database
        Add(new TodoItem { Name = "Item1" });
        //Add(new TodoItem { Name = "Item2" });
        //Add(new TodoItem { Name = "Item3" });
    }

    public IEnumerable<TodoItem> GetAll()
    {
       return _context.TodoItems.AsNoTracking().ToList();
    }

    public void Add(TodoItem item)
    {
        _context.TodoItems.Add(item);
        _context.SaveChanges();
    }

    public TodoItem Find(long key)
    {
        return _context.TodoItems.AsNoTracking().FirstOrDefault(t => t.Key == key);
    }

    public void Remove(long key)
    {
        var entity = _context.TodoItems.AsNoTracking().First(t => t.Key == key);
        _context.TodoItems.Remove(entity);
        _context.SaveChanges();
    }

    public void Update(TodoItem item)
    {
        _context.TodoItems.Update(item);
        _context.SaveChanges();
    }
}

Any help would be appreciated
Regards,

Tony


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>