Entity framework在验证未通过的时候默认不会抛出详细异常,这给我们debug带来很大的困难,不过我们可以手动捕获,见代码:
private int Update(Employee entity)
{
string error = string.Empty;
using (NorthwindEntities ctx = new NorthwindEntities())
{
try
{
//ctx.Employees.Attach(entity);
ctx.Entry(entity).State = System.Data.EntityState.Modified;
return ctx.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var item in ex.EntityValidationErrors)
{
foreach (var item2 in item.ValidationErrors)
{
error = string.Format("{0}:{1}\r\n", item2.PropertyName, item2.ErrorMessage);
}
}
}
}
return 1;
}