c# - 即使使用值 Entity Framework ,实体属性也为空

标签 c# entity-framework-6

因此,出于某种原因,当我尝试执行 db.SaveChanges 时,它说属性 Username 不允许插入空值,但当我使用调试器时它不为空。项目用户名属性中有一个字符串...

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

我首先使用数据库,这是 xUtilizador 类

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

编辑

我还必须创建部分和元数据类来更新数据库中的默认值

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

编辑

另外我刚刚注意到用户名 StoreGeneratedPattern 出于某种原因被设置为 Computed 并且我从未在数据库中给它任何默认值..

最佳答案

问题是用户名在 StoreGeneratedPattern 的模型上被设置为 Computed。确保将其设置为 none 以在插入时不给出 null 异常。

关于c# - 即使使用值 Entity Framework ,实体属性也为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55162996/

相关文章:

c# - Linq to NHibernate OrderBy 枚举值

c# - 通过设置垃圾收集 bool 值来提高 150% 的速度?

c# - 在 Winforms 项目中使用 DataGrid 中的复选框列

C# 公开术语

C# 使用 MySQL 从 EF6 Code-First DB 获取错误的十进制值

c# - 在 Windows 8 Metro App (C#/XAML) 中同时播放两种声音

c# - 如何使用linq从表中获取最大id

c# - LINQ 和 EF6 : The context cannot be used while the model is being created

visual-studio - 从 Visual Studio 发布时,dbo.__MigrationHistory 表未更新

c# - 错误 : Multiple object sets per type are not supported