我在使用EF Core 2.2.3更新.Net Core 2.2.0中的实体时遇到问题。
保存更改时发生错误。错误详细信息:无法跟踪实体类型'Asset'的实例,因为已经跟踪了具有相同键值的{'Id'}的另一个实例。附加现有实体时,请确保仅附加一个具有给定键值的实体实例。考虑使用
这是注册数据库上下文的方式:
services.AddDbContext(options =>
options.UseSqlServer(Configuration.GetConnectionString("DbConnection")), ServiceLifetime.Scoped);
Run Code Online (Sandbox Code Playgroud)
该Scoped生命周期是默认设置,但我写的更容易理解。
该Anomaly对象是这样的:
public IQueryable<Anomaly> GetAll()
{return _context.Anomalies.Include(a => a.Asset).Include(a => a.Level)
}
public async Task<Anomaly> GetAnomaly(int anomalyId, User user)
{
var anomaly = await GetAll()
.FirstOrDefaultAsync(a => a.Id == anomalyId);
return anomaly;
}
Run Code Online (Sandbox Code Playgroud)
该Update()方法如下所示:
using (var transaction = _context.Database.BeginTransaction())
{
try
{
_context.Anomalies.Update(anomaly);
_context.SaveChanges();
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw;
}
}
Run Code Online (Sandbox Code Playgroud)
它包含此事务之前的一些检查,但在此上下文中没有足够的相关性。
这是我已经跟踪实例的错误所在。我不明白这是如何发生..如果上下文Scoped,然后
...“在每种情况下,将为每个请求创建一个新的服务实例”
如果我在PUT请求上的上下文与GET请求的上下文不同,那么如何跟踪实体?在最基本的层面上如何运作?
使它工作的唯一方法是设置下,从所有条目 …
c# entity-framework entity-framework-core .net-core asp.net-core