[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "StaffID,StartDate,EndDate,LeaveType,NoOfDays,AppStatus,HiddenID,LeaveReason,UpdateDate,UpdatedBy")] CurrentApplication currentApplication, Staff staff)
{
if (ModelState.IsValid)
{
db.CurrentApplications.Add(currentApplication);
currentApplication.UpdateDate = System.DateTime.Now;
currentApplication.AppStatus = "PENDING";
currentApplication.UpdatedBy = User.Identity.Name;
var model = new LeaveIndexData();
var userEmail = User.Identity.Name;
model.Staffs = db.Staffs.Single(i => i.Email == userEmail);
var userID = model.Staffs.StaffID;
currentApplication.StaffID = userID;
//decimal period = (currentApplication.StartDate.Date - currentApplication.EndDate.Date).TotalDays;
//currentApplication.NoOfDays = period;
TimeSpan tSpan = (currentApplication.EndDate.Value).Subtract(currentApplication.StartDate.Value);
currentApplication.NoOfDays = tSpan.Days + 1;
db.Staffs.Add(staff);
staff.BalanceLeave = staff.BalanceLeave - currentApplication.NoOfDays;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(currentApplication);
}
我的上面的创建给了我错误Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
它很好并且完美地工作直到我添加这两行:
db.Staffs.Add(人员);
staff.BalanceLeave = staff.BalanceLeave - currentApplication.NoOfDays;
我认为这样做会很好,因为我在db.Staffs中添加的方式与CurrentApplications相同,但它意外地给了我错误。我也不确定如何解决它。
我的员工模型如下所示:
public partial class Staff
{
public int StaffID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public Nullable<decimal> AllocatedLeave { get; set; }
public Nullable<decimal> BalanceLeave { get; set; }
}
我知道有类似的问题,但那些是关于如何找到错误。我知道现在的错误是什么,但是我无法弄清楚为什么我会这样做,因为它对我来说似乎是正确的。请帮忙!谢谢:))
答案 0 :(得分:0)
我认为这可以帮助您验证确切的错误,并且您还可以向用户输出一些人类可读的消息。
try
{
Db.SaveChanges();
}
catch(DbEntityValidationException ex){
foreach(var property in ex.EntityValidationErrors)
{
string entityName=eve.Entry.Entity.GetType().Name;
foreach(var error in property.ValidationErrors)
{
Debug.WriteLine("Table name: "+entityName+" "+ error.PropertyName+" : "+error.ErrorMessage);
}
}
}
答案 1 :(得分:0)
要查看EntityValidationErrors,请将以下监视表达式添加到您的wacth窗口:
((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors