Wednesday, October 12, 2011

Catch Oracle error for Entity Framework update

In this example you have a unique constraint on a column(s) and you want to have the error returned to a label on the current page, allowing the user to correct their data entry. I am not using on linq or Entity Sql to do the update.

Here is some code from the details view, notice we are using the OnItemInserted call to the code behind.

DetailsView ID="DetailsView" runat="server" Height="50px" Width="125px"
AutoGenerateRows="False" DataKeyNames="TIMESHEET_ID" AutoGenerateInsertButton="True" DefaultMode="Insert"
DataSourceID="TimesheetEntityModel" OnModeChanging="OnModeChanging1" OnItemInserted="DetailsViewInserted"




-----

Here is the C# code behind to trap the Oracle error

protected void DetailsViewInserted(object sender, DetailsViewInsertedEventArgs e)
{

if (e.Exception != null)
{
MessageLabel.Text = e.Exception.InnerException.Message;
e.ExceptionHandled = true;
e.KeepInInsertMode = true;


}



-----
This will just send the Oracle error back, It may still be too cryptic for users. You can add a contains like .InnerException.Message.Contains("ORA-123456") to search the error message and send back something more refined.


I have added the OnModeChanging function for reference. It returns the user to the main page if they hit cancel.

protected void OnModeChanging1(object sender, DetailsViewModeEventArgs e)
{


if (e.NewMode == DetailsViewMode.Edit || e.NewMode == DetailsViewMode.Insert)
{
if (e.CancelingEdit)
{
//canceled
MessageLabel.Text = "Insert cancelled.";
//Response.Redirect("~/Timesheet.aspx");
}
else
{

//MessageLabel.Text = "Insert completed.";
Response.Redirect("~/Timesheet.aspx");
}

}

1 comment:

  1. Steven

    This is even better than Entity Framework:
    https://www.kellermansoftware.com/p-47-net-data-access-layer.aspx

    ReplyDelete