【发布时间】:2021-05-28 15:38:48
【问题描述】:
我的应用程序遇到了这个已知问题。 我已经对 HasKey 和 HasAlternateKey 进行了很多更改,甚至是 HasIndex、Unique 和 OnModelCreateCreating() 方法的其他变体。 我什至重新映射了我的实体,但仍然没有成功!
无法跟踪实体类型“Imoveis”的实例,因为 另一个具有键值“{Cod: 91}”的实例已经存在 跟踪。附加现有实体时,确保只有一个实体 附加了具有给定键值的实例。
我的 BaseRepository 类的 Update() 方法:
public T Update(T entity)
{
DbContext.Entry(entity).State = EntityState.Modified; <-- Exception happens here
DbContext.SaveChanges();
return entity;
}
如何调用 Update()。这个问题发生在两个电话上。第二次尝试是防止此错误的失败方法:
public Imoveis InsertOrUpdateUniqueName(Imoveis imoveis)
{
try
{
if (imoveis.Cod > 0)
Update(imoveis);
else
Insert(imoveis);
return imoveis;
}
catch (Exception ex)
{
if (imoveis.Cod > 0)
{
if (ex is DbUpdateException)
{
if ((ex.InnerException as SqlException)?.Number == 2627)
return UpdateImovelDuplicado(imoveis);
}
else if (ex is InvalidOperationException)
{
var local = DbContext
.Set<Imoveis>()
.Local
.FirstOrDefault(x => x.Cod.Equals(imoveis.Cod));
if (local != null)
DbContext.Entry(local).State = EntityState.Detached;
return Update(imoveis);
}
}
throw ex;
}
}
【问题讨论】:
-
我想说 SQL 在这里是无关紧要的。您能否说明
Update是如何被调用的以及entity来自哪里? -
@GuruStron 谢谢!我已经更新了 Update() 调用。我正在维护 SQL,因为其他人可以使用它。
-
您如何管理 DbContext 生命周期?
-
@DavidBrowne-Microsoft 我正在使用在依赖注入设置期间创建的单个 DbContext 实例并通过 ServiceCollection.AddDbContext() 注入它
-
你不能使用单例。采取look here
标签: c# sql sql-server entity-framework orm