我是EntityFramework和ASP.Net的新手
我正在使用EF在Asp.net MVC5中创建一个身份验证系统,我的数据库中有以下字段
Id | Name | Contact | Url | Username | Password
我的模型Clients.cs
的类Clients
需要存储在数据库中:
public class Clients
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public long? Contact { get; set; }
[Required]
[Display(Name = "Site Url")]
public string Url { get; set; }
[Required]
public string Username { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Required]
[Compare("Password", ErrorMessage = "Password Mismatched. Re-enter your password")]
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
public string ConfirmPassword { get; set; }
}
我尝试存储凭证,如下所示:
//Controller::
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Clients clients)
{
if (ModelState.IsValid)
{
Clients client = new Clients();
client.Name = clients.Name;
client.Password = clients.Password;
client.Url = clients.Url;
client.Username = clients.Username;
client.Contact = clients.Contact;
dbContext.Clients.Add(client);
dbContext.SaveChanges();
return RedirectToAction("api/products");
}
return View();
}
显示错误:
Server Error in '/ProductsApp' Application.
Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
Source Error:
Line 32:
Line 33: dbContext.Clients.Add(client);
Line 34: dbContext.SaveChanges();
Line 35: return RedirectToAction("Index");
Line 36: }
如何将所有字段存储在除ConfirmPassword
字段之外的数据库中。
答案 0 :(得分:1)
[NotMapped]
public string MyProperty { get; set; }
您的财产将成为:
[Required]
[Compare("Password", ErrorMessage = "Password Mismatched. Re-enter your password")]
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[NotMapped]
public string ConfirmPassword { get; set; }
答案 1 :(得分:0)
我在Marthijn
的帮助下解决了问题我将客户端确认密码更改为:
[Compare("Password", ErrorMessage = "Password Mismatched. Re-enter your password")]
[DataType(DataType.Password)]
[Display(Name = "Confirm Password")]
[NotMapped]
public string ConfirmPassword { get; set; }
和Controller的代码为:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(Clients clients)
{
if (ModelState.IsValid)
{
dbContext.Clients.Add(client);
dbContext.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
它有效.... 感谢Marthijn