简体   繁体   English

无法跟踪实体类型的实例,因为已在跟踪具有相同键值的另一个实例

[英]The instance of entity type cannot be tracked because another instance with the same key value is already being tracked

I'm getting a same key value runtime exception from entity base class.我从实体库 class 获得了相同的键值运行时异常。 I tried few online solutions with no lucks.我尝试了一些没有运气的在线解决方案。 Can anyone help me to fix this issue?谁能帮我解决这个问题? Following line throwing Exception when I try to update:当我尝试更新时,以下行抛出异常:

this.RepositoryContext.Set().Update(entity); this.RepositoryContext.Set().Update(entity);

Framework: .netcore 3.1框架:.netcore 3.1

Error:错误:

{"The instance of entity type 'JobConnection' cannot be tracked because another instance with the same key value for {'JobConnectionId'} 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."}. {“无法跟踪实体类型'JobConnection'的实例,因为已经在跟踪另一个具有与{'JobConnectionId'}键值相同的实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例. 考虑使用“DbContextOptionsBuilder.EnableSensitiveDataLogging”来查看冲突的键值。”}。

Here is the call:这是电话:

public void UpdateJobConn(JobConnection jobfile)
        {
            Update(jobfile);
            Save();
        }

Here is the whole Repository class:这是整个存储库 class:

using Foreside.Etp.Contracts;
using Foreside.Etp.Entities.Models;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Linq;

namespace Foreside.Etp.Repository
{
    public abstract class RepositoryBase<T> : IRepositoryBase<T> where T : class
    {
        protected EtpRepoContext RepositoryContext { get; set; }

        public RepositoryBase(EtpRepoContext repositoryContext)
        {
            this.RepositoryContext = repositoryContext;
        }

        public IEnumerable<T> FindAll()
        {
            return this.RepositoryContext.Set<T>();
        }

        public IEnumerable<T> FindByCondition(Expression<Func<T, bool>> expression)
        {
            return this.RepositoryContext.Set<T>().Where(expression);
        }

        public void Create(T entity)
        {
            this.RepositoryContext.Set<T>().Add(entity);
        }

        public void Update(T entity)
        {
            this.RepositoryContext.Set<T>().Update(entity);
        }

        public void Delete(T entity)
        {
            this.RepositoryContext.Set<T>().Remove(entity);
        }

        public void Save()
        {
            this.RepositoryContext.SaveChanges();
        }
    }
}

JobConnection Model -作业连接 Model -

public partial class JobConnection
    {
        public int JobConnectionId { get; set; }
        public int KeyId { get; set; }
        public int ConnectionId { get; set; }
        public string Directory { get; set; }
        public int JobId { get; set; }
        public int ConnectiontypeId { get; set; }
    }

Context -语境 -

 public virtual DbSet<JobConnection> JobConnection { get; set; }

modelBuilder.Entity<JobConnection>(entity =>
        {
            entity.ToTable("job_connection");

            entity.HasKey(e => e.JobConnectionId);

            entity.Property(e => e.JobConnectionId)
                .HasColumnName("jobconnectionid")
                .HasColumnType("int(11)");

            entity.Property(e => e.ConnectionId)
                .HasColumnName("connectionid")
                .HasColumnType("int(11)")
                .HasDefaultValueSql("0");

            entity.Property(e => e.ConnectiontypeId)
                .HasColumnName("connectiontypeid")
                .HasColumnType("int(11)");

            entity.Property(e => e.Directory)
                .IsRequired()
                .HasColumnName("directory")
                .HasMaxLength(50)
                .IsUnicode(false)
                .HasDefaultValueSql("0");

            entity.Property(e => e.JobId)
                .HasColumnName("jobid")
                .HasColumnType("int(11)");

            entity.Property(e => e.KeyId)
                .HasColumnName("keyid")
                .HasColumnType("int(11)")
                .HasDefaultValueSql("0");
        });

Table -桌子 -

SHOW INDEXES
FROM job_connection

job_connection  0   PRIMARY 1   jobconnectionid A   63              BTREE       

Finally I fixed this issue by detaching the EntityState.最后我通过分离 EntityState 解决了这个问题。 I really appreciate for sharing your thoughts - it helped to think it through.我非常感谢您分享您的想法 - 它有助于思考。 Please find the problem and the correct solution below.请在下面找到问题和正确的解决方案。

Problem:问题:

There was at least an orphan tracked instance preventing from working with the correct instance that I want to update in DB - basically this is a duplicate instance which was interfering when context was trying to update in DB and were not able to save any references for JobConnection.至少有一个孤立跟踪实例阻止使用我想在 DB 中更新的正确实例 - 基本上这是一个重复的实例,当上下文试图在 DB 中更新并且无法保存 JobConnection 的任何引用时,它会干扰. Context was somehow storing references on inserted objects even after leaving scope of their declaration and initialization.即使在离开 scope 的声明和初始化之后,上下文也以某种方式存储了对插入对象的引用。

Solution:解决方案:

There could be multiple ways to solve this issue.可以有多种方法来解决这个问题。 One of the ways is to detach the instance from context in order to avoid similar orphaned duplicate instances which was causing issues for our case.其中一种方法是将实例从上下文中分离出来,以避免类似的孤立重复实例导致我们的案例出现问题。 Here is an example how I fixed in code:这是我如何在代码中修复的示例:

_context.Entry<JobConnection>(jobCon).State = EntityState.Detached;  //Explicitly Detach the orphan tracked instance 

Another example in code that has similar issue and here is the solution.代码中存在类似问题的另一个示例,这里是解决方案。

var inFiles = _filerepository.FindAllInboundFilesByJobId(job.Jobid);
foreach (File inFile in inFiles)
_context.Entry<File>(inFile).State = EntityState.Detached;

Seems like you are not using something like entity.HasKey(a => a.Id);好像您没有使用entity.HasKey(a => a.Id);类的东西to indicate primary key.表示主键。 hence the DB row id is clashing with the object you have in memory that you are trying to update.因此,数据库行 ID 与您尝试更新的 memory 中的 object 冲突。

You should debug and check the id of the object you are updating right before this.RepositoryContext.SaveChanges();您应该在this.RepositoryContext.SaveChanges();之前调试并检查您正在更新的 object 的 ID。 is called.叫做。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无法跟踪实体类型“Item”的实例,因为已跟踪另一个具有与 {'Id'} 相同键值的实例 - The instance of entity type 'Item' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked 无法跟踪实体类型“书签”的实例,因为已经在跟踪具有相同键值 {'ID'} 的另一个实例 - The instance of entity type 'Bookmark' cannot be tracked because another instance with the same key value for {'ID'} is already being tracked 无法跟踪实体类型的实例,因为已跟踪具有相同键值的另一个实例 - The instance of entity type cannot be tracked because another instance with the same key value for is already being tracked 实体类型的实例 <T> 无法跟踪,因为已经跟踪了另一个具有相同的{&#39;Id&#39;}键值的实例 - The instance of entity type <T> cannot be tracked because another instance with the same key value for {'Id'} is already being tracked 无法跟踪实体类型 Model 的实例,因为已跟踪另一个具有相同 {&#39;Id&#39;} 键值的实例 - The instance of entity type Model cannot be tracked because another instance with the same key value for {'Id'} is already being tracked "使用 AsNoTracking() 获取“无法跟踪实体类型的实例,因为已经在跟踪具有相同键值的另一个实例”" - Getting 'The instance of entity type cannot be tracked because another instance with same key value for is already being tracked' with AsNoTracking() 无法跟踪实体类型“Bus”的实例,因为已经在跟踪具有相同键值 {'Id'} 的另一个实例 - The instance of entity type ‘Bus’ cannot be tracked because another instance with the same key value for {‘Id’} is already being tracked 无法跟踪实体类型“AppUser”的实例,因为已跟踪另一个具有与 {'Id'} 相同键值的实例 - The instance of entity type 'AppUser' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked 无法跟踪实体类型“IdentityUser”的实例,因为已跟踪另一个具有与 {'Id'} 相同键值的实例 - The instance of entity type 'IdentityUser' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked 无法跟踪实体类型“产品”的实例,因为已在跟踪具有相同键值的另一个实例 - The instance of entity type 'Product' cannot be tracked because another instance with the same key value is already being tracked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM