instance of entity type cannot be tracked because another instance with same key value is tracked

后端 未结 4 1637
一个人的身影
一个人的身影 2021-02-12 22:48

I\'m using generic repository pattern in asp.net core 2.0 which can not dispose repository object, when I am going to update the entry its updated for one time successfully but

相关标签:
4条回答
  • 2021-02-12 23:11

    This will help you!

    AsNoTracking()
    
    0 讨论(0)
  • 2021-02-12 23:13

    Just like Rudi Visser suggested, you can face this issue when using one entity across multiple data contexts. In my case, it was something similar to this:

    User user = await DataContext.Users.SingleOrDefaultAsync(u => u.Id == "SomeId");
    
    // Switch to UserManager *_*
    var res = await UserManager.ResetPasswordAsync(user, token, password); // Exception thrown
    

    A simple solution would be to try to stick to one DataContext, because UserManager seems to do some attaching and detaching (maybe) in the background. For example:

    User user = await UserManager.FindByIdAsync("SomeId");
    var res = await UserManager.ResetPasswordAsync(user, token, password);
    
    0 讨论(0)
  • 2021-02-12 23:18

    Your DB Context is being shared by multiple requests, meaning that the entity you're editing has been tracked already.

    This is likely because your repository service is a Singleton rather than Scoped, and so your DB Context is being reused with the entity being tracked when it's pulled out, and then put back in to the same instance of the DB Context.

    What you should be doing instead is having a Scoped Repository, which means that a new instance will be created for each request. Likewise, you will also have a per-request DB Context.

    When you register your service it will be using services.AddSingleton<..>

    Change this to services.AddScoped<..>, when you inject it into your controller you will then get a new instance per request and your updates should work fine.

    0 讨论(0)
  • 2021-02-12 23:27

    You need Detached Entry.

    Entry<CustomerBaseInfo>(data).State = EntityState.Detached;
    
    0 讨论(0)
提交回复
热议问题