我从实体基类中得到了一个相同的键值运行时异常。我尝试了一些在线解决方案,但都没有成功。有谁能帮助我解决这个问题?在更新时,下面这行代码会抛出异常:
this.RepositoryContext.Set().Update(entity);
框架: .netcore 3.1
错误信息:
{"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."}.
此处为调用:
public void UpdateJobConn(JobConnection jobfile)
{
Update(jobfile);
Save();
}
这是整个仓库类(Repository 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 模型 -
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