【发布时间】:2020-08-11 14:37:11
【问题描述】:
通过以下代码,我正在尝试使用实体框架将一个新对象插入到我的 PostgreSQL 数据库中:
类坎波
public class campo
{
public int id { get; set; }
public int id_extrator { get; set; }
public string nome { get; set; }
public bool campo_selecionado { get; set; }
}
调用事件:
private void btnSalvarDetalhesExtrator_Click(object sender, EventArgs e)
{
try
{
_campoDal = new CampoDal();
List<campo> listaCampos = new List<campo>();
campo dadosCampo;
for (int a = 0; a < gvCamposExtrator.RowCount; a++)
{
dadosCampo = new campo();
dadosCampo.id_extrator = _idExtrator;
dadosCampo.nome = (string)gvCamposExtrator.Rows[a].Cells["Nome"].Value;
dadosCampo.campo_selecionado = (bool)gvCamposExtrator.Rows[a].Cells["Campo_Selecionado"].Value;
_campoDal.AdicionarCampo(dadosCampo);
}
}
}
添加到数据库
public campo AdicionarCampo(campo dadosCampo)
{
try
{
_dbContext.Campos.Add(new campo
{
nome = dadosCampo.nome,
id_extrator = dadosCampo.id_extrator,
campo_selecionado = dadosCampo.campo_selecionado
}
);
_dbContext.SaveChanges();
return dadosCampo;
}
catch (Exception ex)
{
throw;
}
}
但是,当我尝试执行此操作时,显示以下错误,类似于 SQLTransaction 的 ZombieCheck。
堆栈跟踪器:
em Npgsql.NpgsqlTransaction.CheckReady()
em Npgsql.NpgsqlTransaction.get_DbConnection()
em System.Data.Common.DbTransaction.get_Connection()
em System.Data.Entity.Infrastructure.Interception.DbTransactionDispatcher.Dispose(DbTransaction transaction, DbInterceptionContext interceptionContext)
em System.Data.Entity.Core.EntityClient.EntityTransaction.Dispose(Boolean disposing)
em System.Data.Common.DbTransaction.Dispose()
em System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
em System.Data.Entity.Core.Objects.ObjectContext.SaveChangesToStore(SaveOptions options, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction)
em System.Data.Entity.Core.Objects.ObjectContext.<>c__DisplayClass148_0.<SaveChangesInternal>b__0()
em System.Data.Entity.Infrastructure.DefaultExecutionStrategy.Execute[TResult](Func`1 operation)
em System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
em System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
em System.Data.Entity.Internal.InternalContext.SaveChanges()
em System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
em System.Data.Entity.DbContext.SaveChanges()
em ConectorAditi.DAL.Concrete.CampoDal.AdicionarCampo(campo dadosCampo) na C:\Users\Joao Pedro\source\repos\ConectorAditi\ConectorAditi\DAL\Concrete\CampoDal.cs:linha 29
试图解决这个问题或给出一个临时解决方案,而不是在 catch 块中返回一个 throw,我最初没有在块中写任何东西,或者把它放在返回我试图添加的对象,就好像它已经工作了.
public campo AdicionarCampo(campo dadosCampo)
{
try
{
_dbContext.Campos.Add(new campo
{
nome = dadosCampo.nome,
id_extrator = dadosCampo.id_extrator,
campo_selecionado = dadosCampo.campo_selecionado
}
);
return dadosCampo;
}
catch (Exception ex)
{
return dadosCampo;
}
}
在这个实现中,数据保存在数据库中,但是在每个循环交互中 SaveChanges 保存新对象和已经插入的对象,而不是只插入新实例化对象的数据。
不知道是不是问题,但是下面的代码是指数据库的上下文类
public class ApplicationDataBase : DbContext
{
private readonly string schema;
public DbSet<assunto> Assuntos { get; set; }
public DbSet<atualizacao_campos_realizada> AtualizacoesCamposRealizadas { get; set; }
public DbSet<campo> Campos { get; set; }
public DbSet<carga_realizada> CargaRealizadas { get; set; }
public DbSet<data_base> DataBases { get; set; }
public DbSet<extrator> Extratores { get; set; }
public DbSet<tipo_carga> TiposCargas { get; set; }
public ApplicationDataBase(string schema) : base("dbConectionString")
{
this.schema = schema;
}
protected override void OnModelCreating(DbModelBuilder builder)
{
builder.Conventions.Remove<PluralizingTableNameConvention>();
Database.SetInitializer<ApplicationDataBase>(null);
builder.HasDefaultSchema(this.schema);
base.OnModelCreating(builder);
}
}
有谁知道我在这个实现中可能出错的地方,以及在使用 SaveChanges 时如何解决 NpgsqlTransaction 的“ZombieCheck”问题甚至数据重复问题?我尝试了一些解决方案和实现,但都没有解决这些情况。
编辑:
作为一个临时解决方案,我在 catch 块中添加了以下行,该行从上下文跟踪中删除了添加的实体,通过@Sowmyadhar Gourishetty 的评论找到了这个解决方案:
catch (Exception ex)
{
_dbContext.Entry(dadosCampo).State = EntityState.Detached;
return dadosCampo;
}
但是,我仍然没有找到避免第一张图片中发布的“ZombieCheck”错误的方法,从而阻止它进入 catch 块。如果有人可以提供帮助,我将不胜感激。
【问题讨论】:
-
嗨乔奥。欢迎来到 SO。您提到“下面的错误”,但您没有提供实际错误。请发布完整的堆栈跟踪,以便我们帮助您了解发生了什么。
-
进一步阅读,它似乎不知道主键。这就是它不断插入新行的原因。
-
您总是将对象添加为新记录,当您要编辑现有记录时,您需要明确提及要修改的 EF。检查一次docs.microsoft.com/en-us/ef/ef6/saving/change-tracking/…
-
@JuanR 我添加了堆栈跟踪。谢谢
-
你能把
campo类的定义贴出来吗?
标签: c# database postgresql entity-framework npgsql