简体   繁体   中英

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..

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM