当我填写创建视图并提交它时';s引发DbEntityValidationException
本文关键字:DbEntityValidationException 引发 提交 创建 视图 | 更新日期: 2023-09-27 18:27:28
在这个项目中,我尝试了一个实体框架代码优先的Apporach
Table 'Employee' Id int NOT NULL FirstName nvarchar(50) NOT NULL LastName nvarchar(50) NOT NULL MiddleName nvarchar(50) NULL Address nvarchar(300) NULL Salary decimal(16,2) NULL Email nvarchar(50) NULL
做得很完美。然后我添加了实体框架,添加了EmployeeController
。两个动作方法CCD_ 2&CCD_ 3及其相应的视图。到目前为止都是完美的。
[在此处输入图像描述][1]![在此输入图像描述][2]
然后我为Employee Add做了以下操作:
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(Employee emp)
{
if (ModelState.IsValid)
{
db.Employees.Add(emp);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(emp);
}
当我填充Create
视图并提交时,它抛出了一个DbEntityValidationException
[在此输入图像描述][3]
DbEntityValidationException was unhandled by user code
An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
我的数据库表也没有更新,现在在那里创建了行。
型号定义
public partial class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MiddleName { get; set; }
public string Address { get; set; }
public Nullable<decimal> Salary { get; set; }
public string Email { get; set; }
}
取自此处
将此代码添加到你的post方法中,它应该有助于理解你在输出窗口中得到的错误
[HttpPost]
public ActionResult Create(Employee emp)
{
try
{
if (ModelState.IsValid)
{
db.Employees.Add(emp);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(emp);
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
System.Diagnostics.Debug.WriteLine("Entity of type '"{0}'" in state '"{1}'" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
System.Diagnostics.Debug.WriteLine("- Property: '"{0}'", Error: '"{1}'"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
}
我讨厌我还不能发表评论,这会更容易解决。
无论如何,添加记录时我要做的是,在保存之前绑定字段并创建模型的实例。这也允许您使用ViewModels。
将您的操作更改为此
[HttpPost]
public ActionResult Create([Bind(Include = "FirstName,LastName,MiddleName,Address,Salary,Email")]Employee u)
{
if (ModelState.IsValid)
{
Employee emp = new Employee
{
FirstName = u.FirstName,
LastName = u.LastName,
MiddleName = u.MiddleName,
Address = u.Address,
Salary = u.Salary,
Email = u.Email
};
db.Employees.Add(emp);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(emp);
}
我没有包括Id
字段的值,因为我认为这将是DB生成的。如果没有,那么Id
将需要包含在Bind
中,并且您需要在Employee emp
的初始化中添加代码来填充Id
如果Id
不是DB生成的,因为我看到您的Id
字段不可为空。要测试此操作代码是否有效,可以执行以下操作:
Employee emp = new Employee
{
Id = 1,
FirstName = u.FirstName,
LastName = u.LastName,
MiddleName = u.MiddleName,
Address = u.Address,
Salary = u.Salary,
Email = u.Email
};
1最后一件事,要生成Id
字段DB,请在T-Sql代码中执行此操作
Id int IDENTITY(1,1) NOT NULL PRIMARY KEY
希望这能解决问题,或者至少是第一步。