繁体   English   中英

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

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

我从实体库 class 获得了相同的键值运行时异常。 我尝试了一些没有运气的在线解决方案。 谁能帮我解决这个问题? 当我尝试更新时,以下行抛出异常:

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

框架:.netcore 3.1

错误:

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

这是电话:

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

这是整个存储库 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();
        }
    }
}

作业连接 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; }
    }

语境 -

 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");
        });

桌子 -

SHOW INDEXES
FROM job_connection

job_connection  0   PRIMARY 1   jobconnectionid A   63              BTREE       

最后我通过分离 EntityState 解决了这个问题。 我非常感谢您分享您的想法 - 它有助于思考。 请在下面找到问题和正确的解决方案。

问题:

至少有一个孤立跟踪实例阻止使用我想在 DB 中更新的正确实例 - 基本上这是一个重复的实例,当上下文试图在 DB 中更新并且无法保存 JobConnection 的任何引用时,它会干扰. 即使在离开 scope 的声明和初始化之后,上下文也以某种方式存储了对插入对象的引用。

解决方案:

可以有多种方法来解决这个问题。 其中一种方法是将实例从上下文中分离出来,以避免类似的孤立重复实例导致我们的案例出现问题。 这是我如何在代码中修复的示例:

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

代码中存在类似问题的另一个示例,这里是解决方案。

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

好像您没有使用entity.HasKey(a => a.Id);类的东西表示主键。 因此,数据库行 ID 与您尝试更新的 memory 中的 object 冲突。

您应该在this.RepositoryContext.SaveChanges();之前调试并检查您正在更新的 object 的 ID。 叫做。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM