【发布时间】:2015-11-29 06:47:51
【问题描述】:
在我的 metadata.cs 文件中,这适用于我在 AddRecord 控制器操作中点击 _db.SaveChanges() 时。 "[AssertThat(" 适用于 Add SaveChanges(),但不适用于 Edit SaveChanges()。 “[必需]”适用于两者。 “sss”不会传递 Add SaveChanges(),它会传递 Edit SaveChanges()。
[Required(ErrorMessage = "Email is required")]
[AssertThat("IsEmail(Email)",ErrorMessage="Valid email format required")]
public string Email { get; set; }
换句话说: 在 EditRecord Controller Action 中,只有正常的 DataAnnotation 会触发,而不是我安装的 ExpressiveAnnotations 并在条件注释中非常好用。添加和编辑操作都在同一个控制器中。并且在单步执行代码时都使用 Overide SaveChanges(),Edit Action 在覆盖的最后一行中断并显示错误中的错误,但不会像 Add View SaveChanges() 那样在输入下显示 ErrorMessage。
public override int SaveChanges()
{
try
{
return base.SaveChanges();
}
catch (DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
最后一行是编辑操作因错误而停止的地方:
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
我通过研究 StackOverflow 得到了上述异常循环和覆盖,非常感谢,当电子邮件不符合有效格式时,它确实捕获了 ExpressiveAnnotations 错误,但它因黄屏死机而窒息。添加或拒绝记录后,我的添加操作不会阻塞并继续执行。
我希望我已经提供了足够的信息。我查看了这两个视图,它们实际上是相同的。
几个小时后
我想也许我在调用 Actions 时没有从视图中发送正确的模型。
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditStoreAccount(int id, FormCollection formValues)
{
var accountToUpdate = _db.StoreAccounts.First(m => m.AccountID == id);
if (ModelState.IsValid)
{
//fill up accountToUpdate
_db.SaveChanges();
下面是我如何执行添加操作:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddStoreAccount(StoreAccounts storeaccounts)
{
if (ModelState.IsValid) {
_db.StoreAccounts.Add(storeaccounts);
{
_db.SaveChanges();
【问题讨论】:
标签: asp.net-mvc asp.net-mvc-5 savechanges expressiveannotations