【问题标题】:Error when executing SaveChanges() with key field on Npgsql在 Npgsql 上使用键字段执行 SaveChanges() 时出错
【发布时间】:2014-03-19 17:55:26
【问题描述】:

从 DbContext 执行 SaveChanges 方法时,我的 Npgsql 模型出现问题:

    A null store-generated value was returned for a non-nullable member 'Id' of type     
'Easylab.DAO.Contextos.LogCad'.

可能Npgsql 在调用SaveChanges 时没有从插入中获取值,或者不理解字段Key 的空值的可能性?

这是模型:

[Table(name: "tab_logcad", Schema = "public")]
public class LogCad
{
    [Display(Name = "Id")]
    [Key, Column("id")]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Column("tabela")]
    [Display(Name = "Tabela")]
    [DataType(DataType.Html)]
    [Required(ErrorMessage = "Nome da tabela requerido")]
    public string Tabela { get; set; }

    [Column("idreg")]
    [Display(Name = "Id do Registro")]
    [Required(ErrorMessage = "Identificador do registro requerido")]
    public int IdReg { get; set; }

    [Column("idopera")]
    [Display(Name = "Id da Operação")]
    [Required(ErrorMessage = "Identificador da operação requerido")]
    public int IdOpera { get; set; }

    [ForeignKey("IdOpera")]
    public virtual Operadores Operador { get; set; }

    [Column("acao")]
    [Display(Name = "Ação")]
    [DataType(DataType.Html)]
    [Required(ErrorMessage = "Descrição da ação requerida")]
    public string Acao { get; set; }

    [Column("motivo")]
    [Display(Name = "Motivo")]
    [DataType(DataType.Html)]
    [Required(ErrorMessage = "Descrição do motivo requerida")]
    public string Motivo { get; set; }

    [Column("data")]
    [Display(Name = "Data")]
    [DataType(DataType.Date)]
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")] //ApplyFormatInEditMode = true, 
    [Required(ErrorMessage = "Informe uma data válida")]
    public DateTime Data { get; set; }

    [Column("hora")]
    [Display(Name = "Hora")]
    [DataType(DataType.Time)]
    [Required(ErrorMessage = "Informe um horário válido")]
    public string Hora { get; set; }

    [Column("maquina")]
    [Display(Name = "Maquina")]
    [DataType(DataType.Html)]
    [Required(ErrorMessage = "Identificação da máquina requerida")]
    public string Maquina { get; set; }

    [Column("tabelapai")]
    [Display(Name = "Tabela Ascendente")]
    [DataType(DataType.Html)]
    public string TabelaPai { get; set; }

    [Column("idregpai")]
    [Display(Name = "Id Registro Ascendente")]
    public int? IdRegPai { get; set; }
}

控制器调用的方法:

[HttpPost]
[Autorizacao(Roles = "ExApoio")]
public ActionResult Excluir(int idReg, string motivo)
{
    var resp = new ContentResult
    {
        ContentType = "application/text",
        ContentEncoding = Encoding.UTF8,
        Content = "Sucess"
    };

    #region Validações
    if (idReg <= 0)
    {
        resp.Content = "O registro a excluir não possui identificação válida";
        Response.StatusCode = (int)HttpStatusCode.ExpectationFailed;
        return resp;
    }
    if (string.IsNullOrWhiteSpace(motivo))
    {
        resp.Content = "O registro não pode ser excluído se não for informado um motivo.";
        Response.StatusCode = (int)HttpStatusCode.ExpectationFailed;
        return resp;
}
    #endregion

    var contexto = new CtxCliente(Sistema.EmpresaCliente.DbConector);
    var pgTrans = contexto.Database.BeginTransaction();
    try
    {
        var idOperador = Util.GetOperadorId(Sistema.EmpresaCliente.SacadoId);             
        var maquina = Util.ObterMaquina();
        RegistrarLogExclusao(ref contexto, idOperador, motivo, maquina, idReg, "apoio");
        var apoio = contexto.DbApoio.Find(idReg);
        contexto.DbApoio.Remove(apoio);
        contexto.Entry(apoio).State = EntityState.Deleted;
        contexto.SaveChanges(); //====== ERROR =========>>>>>> A null store-generated value was returned for a non-nullable member 'Id' of type 'Easylab.DAO.Contextos.LogCad'.
        pgTrans.Commit();
        Response.StatusCode = (int)HttpStatusCode.OK;
        resp.Content = "Dados excluídos com sucesso";
    }
    catch (Exception e)
    {
        pgTrans.Rollback();
        Response.StatusCode = (int)HttpStatusCode.InternalServerError;
        resp.Content = e.Message;
    } 
    return resp;
}

private void RegistrarLogExclusao(ref CtxCliente contexto, int idOperador, string motivo, string maquina, int id, string tabela, int idRegPai = 0, string tabelaPai = "")
{   
    if (contexto == null) 
    throw new ArgumentException("Contexto inválido");
    var log = new LogCad
    {
        IdOpera = idOperador,
        Motivo = motivo,
        Maquina = maquina,
    Data = DateTime.Now.Date,
    Hora = DateTime.Now.ToString("t"),
    Acao = "Exclusão",
    IdReg = id,
    IdRegPai = idRegPai,
    Tabela = tabela,
    TabelaPai = tabelaPai
};
contexto.DbLogCad.Add(log);
contexto.Entry(log).State = EntityState.Added;
}

例外:

A null store-generated value was returned for a non-nullable member 'Id' of type 'Easylab.DAO.Contextos.LogCad'.

【问题讨论】:

  • 嗨,古斯塔沃!我正在检查那个。感谢您的报告。

标签: c# entity-framework asp.net-mvc-4 entity-framework-6 npgsql


【解决方案1】:

解决了! 发生此问题是因为我们的表没有为她的序列提供“适当”的定义。我们用 alter table 定义改变了她的定义,然后……瞧! =D

ALTER SEQUENCE <sequence> OWNED BY <table>.<column>

感谢 Npgsql 团队,尤其是 Francisco Junior (@francisco-junior) 的直接帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-01
    相关资源
    最近更新 更多