C# 无法处理与检查参与者相关的sql异常

C# 无法处理与检查参与者相关的sql异常,c#,sql,.net,sql-server,ado.net,C#,Sql,.net,Sql Server,Ado.net,我正在使用C#win表单和MSSQL服务器编写一个桌面应用程序。在我的数据库中,有这样一个表: create table material( id int identity(700,3), materialName nvarchar(100) not null default (0), unitPrice decimal(19,2) not null default (0), carbohydrate tinyint not null default (0), protein tinyint n

我正在使用C#win表单和MSSQL服务器编写一个桌面应用程序。在我的数据库中,有这样一个表:

create table material(
id int identity(700,3),
materialName nvarchar(100) not null default (0),
unitPrice decimal(19,2) not null default (0),
carbohydrate tinyint not null default (0),
protein tinyint not null default (0),
fat tinyint not null default (0),
humidity tinyint not null default (0) ,
minerals tinyint not null default (0),
constraint PK_id_materialPriceAndStandard primary key (id),
constraint UQ_materialName_materialPriceAndStandard unique (materialName), 
constraint CHECK_totlaMineralAmount check 
(carbohydrate + protein + fat + humidity + minerals =100 )) 
材料表中5个字段的总数不得超过100

在C#中,当用户输入超过100的金额时,我会遇到此异常:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: The INSERT statement conflicted with the CHECK constraint         
"CHECK_totalMineralAmount_materialPrice".
The conflict occurred in database "secaloFormula", table "dbo.materialPrice"
这是连接到数据库并调用存储过程的代码:

public void addMaterial()
    {
        string ConString = ConfigurationManager.ConnectionStrings["secaloFormulaCS"].ToString(); 
        using(SqlConnection sqlCon = new SqlConnection(ConString))
        using(SqlCommand sqlCmd = new SqlCommand("spAddMaterial",sqlCon))
        {
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("materialName", MaterialName); 
            sqlCmd.Parameters.AddWithValue("unitPrice",Price);
            sqlCmd.Parameters.AddWithValue("carbohydrate",Carbohydrtate);
            sqlCmd.Parameters.AddWithValue("proterin", Proterin); 
            sqlCmd.Parameters.AddWithValue("fat",Fat); 
            sqlCmd.Parameters.AddWithValue("humidity", Humadity); 
            sqlCmd.Parameters.AddWithValue("minerals",Minerlas);
            sqlCon.Open();
            sqlCmd.ExecuteNonQuery();
            sqlCon.Close();
            sqlCon.Dispose(); 
        }
    }

如何处理此异常,在插入量超过100时向用户发出警告?

我建议检查业务逻辑中的约束,而不是依赖数据库拒绝任何无效消息。如果您死心塌地地想对业务规则使用约束,那么可以尝试/捕获ExecuteOnQuery并返回抛出的异常

try 
{
   sqlCmd.ExecuteNonQuery();
}
catch (SqlException ex)
{
   // the error should be in the Ex
}

请参阅链接。
这个错误很可能在ex.Errors中


对于使用,我认为您不需要处理,但我怀疑这会损害任何东西

如果您是对的,问题是我阅读了许多来源的教程,这导致了非标准代码!。但是我怎样才能像专业人士一样学习编写代码呢?读一本书。对于.NET,我喜欢Apress的Troelsen。