Asp.net Core EF Update

asp.net-core-mvc entity-framework-core

Question

I used EF in Asp.net Core, but I got below error when trying to Update.

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 Update 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();
    }
}

As you could find, I already have tried AsNoTracking, and I also tried it in Startup.cs.

public void ConfigureServices(IServiceCollection services)
{
    //inject repository into DI container, use database in memory
    services.AddDbContext<TodoContext>(options => options.UseInMemoryDatabase().UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));

    //inject repository into DI container, and use sql databse
    //services.AddDbContext<TodoContext>(options=>options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));


    //The first generic type represents the type (typically an interface) that will be requested from the container. 
    //The second generic type represents the concrete type that will be instantiated by the container and used to fulfill such requests.
    services.AddSingleton<ITodoRepository, TodoRepository>();

    //add mvc service to container, this is conventional routing
    //This also applys to web api which is Attribute Routing
    services.AddMvc();
}

Any help would be appreciated.

1
0
3/2/2017 8:47:00 AM

Accepted Answer

I resolved this issue by changing services.AddDbContext to services.AddScoped which has been pointed out in below link. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection

0
3/22/2017 6:58:52 AM


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