Question

I have 5 different entities for which dynamic data(with LINQTOSQL) was generated. On Insert(Insert.aspx) of any of these entities, if there is an error, I would like to notify user that error happened and possibly show some generic error message.

1) I am not talking about regular required field errors but something like "Unique constraint violation"

2) I can do it for each page separately by doing something like this:

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) BUT, I want to created something very generic that will work for all inserts across all entities

Was it helpful?

Solution 3

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

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

}

OTHER TIPS

You can customize validation by creating an event handler in the ADO.NET Entity Framework class:

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.");
        }

    }
}

Any validation exceptions that are thrown in the data model are caught by the DynamicValidator control. The page templates included with a Dynamic Data project contain a DynamicValidator control, which displays the validations errors on the page.

I can't fully test this for your situation but, you could override the SubmitChanges method.

 public partial class MyNorthwindDataContext : NorthwindDataContext
 {

  public MyNorthwindDataContext()
  {

  }

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

   base.SubmitChanges(failureMode);
  }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top