【问题标题】:Errors in SaveChanges using entity framework and PostgreSQL使用实体框架和 PostgreSQL 的 SaveChanges 错误
【发布时间】: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。

Error ZombieCheck Npgsql

堆栈跟踪器:

   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


【解决方案1】:

我认为您的问题可能是 EF 不知道您的主键是什么。

尝试将以下属性添加到类campo 中的属性id

[Key]
public int id { get; set; }

这个属性可以在命名空间System.ComponentModel.DataAnnotations中找到。

此外,您无需创建新实体。您只需将要传递的那个添加到方法中即可。现在没有必要退回任何东西。此外,如果您只是要重新抛出异常,那么捕获异常是没有意义的。唯一有用的是您需要添加有关方法内部发生的事情的其他信息。

然后你的方法被简化为:

public void AdicionarCampo(campo dadosCampo)
{
    _dbContext.Campos.Add(dadosCampo);
    _dbContext.SaveChanges();
}

话虽如此,您的代码目前总是会添加新记录。如果您希望更新现有对象并仅添加新对象,则您需要先从上下文中检索对象(当它们存在时),更新它们,然后在上下文中调用 SaveChanges 方法。

我要提防的一件事是您保留了一个内部上下文实例 (_dbContext)。这意味着您需要确保上下文在使用时处于正确的状态。上下文旨在用作一个工作单元,因此如果您要允许最终将“提交”在一起的一系列操作,您应该只以这种方式保持它的活动状态。事实上,如果这不能解决您的问题,那么您很可能在这些可能导致问题的调用之前对 DAL(以及上下文)进行了其他操作。

【讨论】:

    猜你喜欢
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    相关资源
    最近更新 更多