无法跟踪实体类型的实例,因为跟踪了另一个具有相同键值的实例 [英] instance of entity type cannot be tracked because another instance with same key value is tracked

查看:36
本文介绍了无法跟踪实体类型的实例,因为跟踪了另一个具有相同键值的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 asp.net core 2.0 中使用通用存储库模式,它无法处理存储库对象,当我要更新条目时,它已成功更新一次,但是当我尝试更新更多时,一旦抛出以下异常:

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 when I am trying to update for more then once it throws the following exception:

无法跟踪实体类型公司"的实例,因为已跟踪具有相同 {'ID'} 键值的另一个实例.附加现有实体时,请确保仅附加一个具有给定键值的实体实例.考虑使用DbContextOptionsBuilder.EnableSensitiveDataLogging"来查看冲突的键值.

The instance of entity type 'Company' cannot be tracked because another instance with the same key value for {'ID'} 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.

public ActionResult Edit(Int64 id, Company collection)
{
    try
    {
        // TODO: Add update logic here
        interfaceobj.updateModel(collection);
        interfaceobj.Save();
        return RedirectToAction(nameof(Index));
    }
    catch(Exception ex)
    {
        throw ex;
    }
}

推荐答案

您的数据库上下文正被多个请求共享,这意味着您正在编辑的实体已被跟踪.

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

这可能是因为您的存储库服务是单例而不是作用域,因此您的 DB Context 正在与被拉出时被跟踪的实体一起重用,然后放回 DB Context 的同一个实例.

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.

您应该做的是拥有一个Scoped Repository,这意味着将为每个请求创建一个新实例.同样,您还将拥有每个请求的数据库上下文.

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.

当您注册您的服务时,它将使用 services.AddSingleton<..>

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

将其更改为 services.AddScoped<..>,当您将其注入控制器时,您将获得每个请求的新实例,并且您的更新应该可以正常工作.

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.

这篇关于无法跟踪实体类型的实例,因为跟踪了另一个具有相同键值的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆