This thread shows how to identify the violation of primary key. So you will have to change your error handling code to something like:
try
{
// Code
}
catch(SqlException ex)
{
if (ex.Number == 2627)
{
MessageBox.Show("An error", "The same value already exists - change some data", MessageBoxIcon.Error, MessageBoxButton.OK);
}
}
It seems that it is safe to assume that 2627 is the code for unique key violation - Unique Key Violation in SQL Server - Is it safe to assume Error 2627?.
It will work for MS SQL, but I doubt that there could be any DB independent method to handle such exceptions.
Proposed solution:
I am not sure that you can get relevant data from the exception to identify the entity(table, column) that is the reason for this exception, so to show really useful error message you will have to localize your error handling or add some exception wrapping code like:
public class SqlDuplicateKeyException : Exception
{
String EntityName
{
get;
private set;
}
String DuplicateKeyValue
{
get;
private set;
}
public SqlDuplicateKeyException(String entityName, String duplicateKeyValue, Exception innerException)
: base(String.Format("The same value {0} already exists in {1} - change it", exc.DuplicateKeyValue, exc.EntityName),
innerException)
{
this.EntityName = entityName;
this.DuplicateKeyValue = duplicateKeyValue;
}
}
try
{
//Your deep model insert(update) logic
}
catch(SqlException exc)
{
if (ex.Number == 2627)
{
throw new SqlDuplicateKeyException("Table", "KeyDuplicateValue", exc);
}
}
try
{
// high level routine that calls deep model code
}
catch(SqlDuplicateKeyException exc)
{
MessageBox.Show("An error",
String.Format("The same value {0} already exists in {1} - change it", exc.DuplicateKeyValue, exc.EntityName),
MessageBoxIcon.Error,
MessageBoxButton.OK);
}
Or taking into account that we have already initialized Message Property with call to the base constructor you could just leave your generic exception handling code:
try
{
// high level routine that calls deep model code
}
catch(Exception exc)
{
MessageBox.Show("An error",
Exception.Message,
MessageBoxIcon.Error,
MessageBoxButton.OK);
}