1. 驗證不過的原因
public ActionResult Create(TopicCategory model)
{
if (ModelState.IsValid)
{
_db.TopicCategory.Add(model);
_db.SaveChanges();
return Json(new { status = "success", information = model.Id });
}
else
{
string messages = string.Join("; ", ModelState.Values
.SelectMany(x => x.Errors)
.Select(x => x.ErrorMessage));
return Json(new { status = "error", information = messages });
}
}
2. EF SaveChanges()失敗原因
try
{
_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);
}
}
}
or
try
{
// Your code...
// Could also be before try if you know the exception occurs in SaveChanges
_db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.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)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}
沒有留言:
張貼留言