我的程序出现问题,无法保存到数据库。我收到"一个或多个实体的验证失败。请参阅' EntityValidationErrors'物业详情。"我上网后发现了一些关于应用Try / Catch" SaveChanges()"的文章。这个项目是MVC。该项目在本地工作没有问题,但当我按下它时,我收到错误消息。
控制器
//
// GET: /Account/LogOff
[Authorize]
public ActionResult LogOff()
{
// get user information
var user = Membership.GetUser();
var userId = (int)user.ProviderUserKey;
var userProfile = db.UserProfiles.Where(up => up.UserId == userId).Single();
// used to display notifications, last login date is set when the user logs off
var profile = db.UserProfiles.Where(up => up.UserId == userId).Single();
profile.LastLoginDate = DateTime.Now.AddHours(2);
db.Entry(profile).State = EntityState.Modified;
try
{
// doing my logic here
db.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}", validationError.
PropertyName, validationError.ErrorMessage);
}
}
}
FormsAuthentication.SignOut();
return RedirectToAction("LogOn", "Account"); // return user to login screen
}