Domanda

I have a problem with my Npgsql model when execute SaveChanges method from a DbContext:

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

Maybe Npgsql doesn't get the value from insert or not understand the possibility of a null value for a field Key when SaveChanges called?

This is the model:

[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; }
}

The methods called on controller:

[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;
}

Exception:

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

Soluzione

Solved! This problem occured because our tables were not with an "adequate" definition for her sequences. We changed her definitions with a alter table definition and... voilà! =D

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

Thanks for Npgsql Team and especially for Francisco Junior ( @francisco-junior ) for their direct help.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top