Search code examples
c#sql-serverexceptionsqlexceptionunique-key

How to find which column throws unique key constraint exception when there are more than one unique key columns in table?


I am new to C# .NET. I have been trying since 2 days, but I couldn't succeed.
I have created windows application. I have table which has two unique columns email,phone.
I want to find the column name which throws the unique key constraint exception at the time of insertion of record. I tried,
var ex = new SqlException();
ex.Data["Mesg"] = "Exception in Email";
throw ex;

But it leads to Error "System.Data.SqlClient.SqlException' has no constructors defined "
Is it possible? Help me.


Solution

  • You want to obtain this information, not produce it. So use the following construct:

    try
    {
        ... (access the database here) ...
    }
    catch (SqlException e)
    {
        ... (look at e.Message)
    }