实体属性为空,即使使用值实体框架
作者:互联网
因此出于某种原因,当我尝试执行db.SaveChanges时,它说属性Username不允许插入null值,但在使用调试器时不为null.项目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的模型上将用户名设置为“已计算”.确保将其设置为none以在插入时不给出null异常.
标签:entity-framework-6,c 来源: https://codeday.me/bug/20191211/2105701.html