我想將我的註冊表格中的數據發佈到我的數據庫中。起初,我有一個非常常見的錯誤「實體類型<model>
不是當前上下文的模型的一部分」 。我解決了它,然後出現了另一個錯誤。所以現在出現的錯誤是在SaveChanges部分,它是「找不到實體密碼」。我該如何解決這個問題?實體框架DbEntityValidationException - 找不到實體
這裏是我的上下文的代碼。
public partial class MyDbEntities : DbContext
{
public MyDbEntities()
: base("name=MyDbEntities")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().ToTable("Users");
modelBuilder.Entity<User>().Property(u => u.Name).IsRequired().HasMaxLength(256);
modelBuilder.Entity<User>().Property(u => u.Surname).IsRequired().HasMaxLength(256);
modelBuilder.Entity<User>().Property(u => u.Email).IsRequired().HasMaxLength(200);
modelBuilder.Entity<User>().Property(u => u.password).IsRequired().HasMaxLength(100);
modelBuilder.Entity<User>().Property(u => u.address).IsRequired();
modelBuilder.Entity<User>().Property(u => u.postcode).IsRequired();
modelBuilder.Entity<User>().Property(u => u.number).IsRequired();
}
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
string errorMessages = string.Join("; ", ex.EntityValidationErrors.SelectMany(x => x.ValidationErrors).Select(x => x.ErrorMessage));
throw new DbEntityValidationException(errorMessages);
}
}
public virtual DbSet<User> Users { get; set; }
}
這裏是我的控制器
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(User U)
{
using(MyDbEntities db=new MyDbEntities())
{
db.Users.Add(U);
db.SaveChanges();
ModelState.Clear();
U = null;
ViewBag.Message("Seccesfully stored");
}
return View(U);
}
的代碼和模型 `
[Required]
[Display(Name = "Name")]
public string Name { get; set; }
[Required]
[Display(Name = "Surname")]
public string Surname { get; set; }
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[DataType (DataType.Password)]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[Display(Name = "Password")]
public string password { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
[Required]
[Display(Name = "Address")]
public string address { get; set; }
[Required]
[Display(Name = "PostVode")]
[DataType(DataType.PostalCode)]
public string postcode { get; set; }
[Required]
[Display(Name = "Phone Number")]
public string number { get; set; }
請張貼精確的錯誤 – Luke
清楚,不是很容易的,因爲錯誤是希臘文寫成的,但我會翻譯。它表示無法找到名稱爲「密碼」的實體。 –
哈哈哈。好吧。那麼我能想到的唯一的事情就是''''''''''''''''''''''屬性上有'[Required]'屬性,並且你還沒有設置它,或者它沒有設置在'User U'參數上正在傳遞給你的方法。 – Luke