我有5个不同的实体,其中生成了动态数据(使用LINQTOSQL)。 在任何这些实体的Insert(Insert.aspx)上,如果有错误,我想通知用户发生错误并可能显示一些通用错误消息。

1)我不是在讨论常规的必填字段错误,而是“独特的约束违规”

2)我可以通过以下方式分别为每个页面执行此操作:

protected void DetailsView1_ItemInserted(object sender, DetailsViewInsertedEventArgs e) {
    if (e.Exception == null || e.ExceptionHandled)
    {
        Response.Redirect(table.ListActionPath);
    }
    else
    {
        //OtherErrors is the label on the page
        OtherErrors.Visible = true;
        OtherErrors.Text = e.Exception.Message;
        OtherErrors.DataBind();
        e.ExceptionHandled = true;
        e.KeepInInsertMode = true;

    }
}

3)但是,我想创建一些非常通用的东西,适用于所有实体的所有插页

有帮助吗?

解决方案 3

    public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
{

    try
    {
        base.SubmitChanges(failureMode);
    }
    catch (Exception e)
    {
        throw new ValidationException("Something is wrong", e);
    }

}

其他提示

您可以通过在ADO.NET Entity Framework类中创建事件处理程序来自定义验证:

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.DynamicData;
using System;
using System.Data;
using System.Data.Objects;

namespace AdventureWorksLTModel 
{
    public partial class AdventureWorksLTEntities 
    {
        partial void OnContextCreated() 
        {
            this.SavingChanges += new System.EventHandler(OnSavingChanges);
        }

        public void OnSavingChanges(object sender, System.EventArgs e) 
        {
            var stateManager = ((AdventureWorksLTEntities)sender).ObjectStateManager;
            var changedEntities = ObjectStateManager.GetObjectStateEntries (EntityState.Modified | EntityState.Added);

            // validation check logic
            throw new ValidationException("Something went wrong.");
        }

    }
}

DynamicValidator控件捕获数据模型中抛出的任何验证异常。动态数据项目附带的页面模板包含DynamicValidator控件,该控件在页面上显示验证错误。

我无法根据您的情况对此进行全面测试,但您可以覆盖 SubmitChanges 方法。

 public partial class MyNorthwindDataContext : NorthwindDataContext
 {

  public MyNorthwindDataContext()
  {

  }

  public override void SubmitChanges(System.Data.Linq.ConflictMode failureMode)
  {
   //catch error logic here...

   base.SubmitChanges(failureMode);
  }
 }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top