SqlException constraint violation

守給你的承諾、 提交于 2019-12-23 15:09:39

问题


I'm working on an asp.net app. Is there a way, when catching a SqlException, to know which constraint was violated?


回答1:


SqlException has a collection of SqlError objects: Errors. The SqlError have properties for error Number and you can compare this with the known constraint violation error numbers (eg. 2627).

While is true that SqlException itself exposes a Number property, it is not accurate if multiple errors happen in a single batch and hence is better to inspect the Errors collection.




回答2:


catch (SqlException ex)
{
    if (ex.Errors.Count > 0) // Assume the interesting stuff is in the first error
    {
        switch (ex.Errors[0].Number)
        {
            case 547: // Foreign Key violation
                throw new InvalidOperationException("Your FK user-friendly description", ex);
                    break;
            // other cases
        }
    }
}



回答3:


You have to add exception handler for the ConstraintException if I understand your question correctly

try
{

}
catch(ConstraintException exc)
{
//exc.Message 
}



回答4:


Are you letting the exception bubble up? If you don't catch it and turn custom errors off in the web.config i believe it will display it in your browser. If you are catching it i would put a break point in the catch section and inspect the exception there.




回答5:


The best thing is to catch this catch exception in your C# code behind.

catch(SqlException ex)
{
    if (ex.Message.Contains("UniqueConstraint"))
        throw new UniqueConstraintException();

    throw;
} 

You can create your own exception and throw that from your data layer, otherwise you can directly catch the exception as mentioned above.

using System; 

public class UniqueConstraintException : Exception
{
} 


来源:https://stackoverflow.com/questions/2517064/sqlexception-constraint-violation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!