如何得到确切"约束名"从的SQLException [英] How to get the exact "constraint name" from SQLException
本文介绍了如何得到确切"约束名"从的SQLException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法得到确切的约束名在C#中的Microsoft SQL异常,\索引名错误号2601或2627,但没有解析消息财产的文字?
例如:
赶上(SQLEXCEPTION E)
{
开关(e.Number)
{
案例2601:
/ *在这里,我想知道的情况下,约束名我有
多个在特定的表,所以我就能够
显示正确的错误信息给使用者。
例如:
案例IX_Username:
抛出新的异常(用户名重复)
案例IX_PhoneNumber:
抛出新的异常(联系号码重复)
* /
打破;
默认:
扔;
}
}
解决方案
使用命名为约束条件,例如约定命名这些总是包含强调像 FK_Xxx
或 UQ_Xxx
然后用正则表达式解析错误,像这样的名字
VAR匹配= Regex.Matches(外键FK_Xxx冲突。,@\ B \ W * _ \宽* \ B)
.Cast<匹配>()FirstOrDefault()。
回到比赛!= NULL? match.Value:空;
Is there a way to get the exact "constraint name"\"index name" from C# "Microsoft SQL Exception", Error number 2601 or 2627, but without parsing the text of the "Message property"?
For example:
catch (SqlException e)
{
switch (e.Number)
{
case 2601:
/* Here i want to know the constraint name in case i have
more than one on a specific table, so i will be able to
display the correct error message to the user.
For example:
case IX_Username:
throw new Exception("Username duplication")
case IX_PhoneNumber:
throw new Exception("PhoneNumber duplication")
*/
break;
default:
throw;
}
}
解决方案
Use naming convention for constraints e.g. name these to always contain underscore like FK_Xxx
or UQ_Xxx
then use regex to parse errors for names like this
var match = Regex.Matches("Foreign key FK_Xxx violation.", @"\b\w*_\w*\b")
.Cast<Match>().FirstOrDefault();
return match != null ? match.Value : null;
这篇关于如何得到确切&QUOT;约束名&QUOT;从的SQLException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文