Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity property is null even with value entity framework

So for some reason when I try to do db.SaveChanges it says the property Username is not allowed to have null value inserted yet it is not null when I use debugger. The item Username property has a string in it...

public void fvAddUser_InsertItem()
{
    var item = new InventarioCiclico.xUtilizador();

    TryUpdateModel(item);

    if (ModelState.IsValid)
    {
        using (InventarioCiclicoContext db = new InventarioCiclicoContext())
        {
            if (db.xUtilizador.Any(u => u.Username == item.Username))
            {
                Page.ClientScript
                    .RegisterStartupScript(
                        this.GetType(),
                        "ShowToast",
                        "ShowToast('Erro','topCenter','error', 'Utilizador já exsiste.', '2000')",
                        true
                    );
            }
            else
            {
                xColaborador c = new xColaborador();
                c.Nome = (fvAddUser.FindControl("txtNome") as TextBox).Text;
                c.Email = (fvAddUser.FindControl("txtEmail") as TextBox).Text;
                item.xColaborador.Add(c);

                db.xUtilizador.Add(item);
                db.SaveChanges();
                Page.ClientScript
                    .RegisterStartupScript(
                        this.GetType(),
                        "ShowToast",
                        "ShowToast('OK', 'topCenter','success', 'Utilizador adicionado com sucesso.', '2000')",
                        true
                    );
            }
        }
    }
}

I'm using database first, this is the xUtilizador class

public partial class xUtilizador
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public xUtilizador()
    {
        this.Activo = true;
        this.xAcesso = new HashSet<xAcesso>();
        this.xColaborador = new HashSet<xColaborador>();
    }

    public int UserID { get; set; }
    public string Username { get; set; }
    public bool Activo { get; set; }
    public Nullable<System.DateTime> UltimoAcesso { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<xAcesso> xAcesso { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<xColaborador> xColaborador { get; set; }
}

EDIT

I also had to create partial and metadata classes to update the default value in database

 [MetadataType(typeof(Metadata.UtilizadorMetadata))]
    public partial class xUtilizador
    {
        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public bool Activo { get; set; }
    }

 public class UtilizadorMetadata
    {
        [StringLength(8)]
        [Display(Name="Username")]
        public string Username;

        [DatabaseGenerated(DatabaseGeneratedOption.Computed)]
        public bool Active;
    }

EDIT

Also I just noticed the Username StoreGeneratedPattern is set to Computed for some reason and I never gave it any default values on database..

like image 337
Jackal Avatar asked Dec 21 '25 21:12

Jackal


1 Answers

The problem was username was being set as Computed on the model on StoreGeneratedPattern. Make sure it is set to none to not give null exception on insert.

like image 166
Jackal Avatar answered Dec 23 '25 11:12

Jackal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!