Search code examples
asp.netentity-frameworkdynamic-data

Handle database insert conflict in ASP.NET Dynamic Data with ADO.NET Entity Data Model


I'm working on an ASP.NET Dynamic Data Entities project with Visual Studio 2013. My data source is an ADO.NET Entity Data Model based on a SQL Server database.

When I try to insert a new table entry that violates a unique key constraint I get a quite user-unfriendly error page with the whole stack trace. Is it possible to just display a short error message in the Insert-view? (similar to the error message when a required field is left empty)

What I tried so far is to extend the following code in Insert.aspx.cs

protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e) {
    if (e.Exception == null || e.ExceptionHandled) {
        Response.Redirect(table.ListActionPath);
    }
}

to this (checking on the unique key conflict with exception number 2627)

protected void FormView1_ItemInserted(object sender, FormViewInsertedEventArgs e) {
    if (e.Exception == null || e.ExceptionHandled) {
        Response.Redirect(table.ListActionPath);
    }
    else
    {
        SqlException innerException = e.Exception.InnerException as SqlException;
        if (innerException != null)
        {
            if (innerException.Number == 2627)
            {
                // Violation of unique constraint
                throw new ValidationException("Unique key violation");
            }
        }
    }
}

Although Insert.aspx uses an asp:DynamicValidator I get the the following exception: "ValidationException was unhandled by user code."

Does anyone know what to do here? Thanks a lot.


Solution

  • I found a solution. Apparently there are some issues with ValidationExceptions in EF.

    http://forums.asp.net/t/1476131.aspx

    http://blogs.msdn.com/b/davidebb/archive/2008/12/11/handling-database-exceptions-in-dynamic-data.aspx