行の挿入時にUNIQUE KEY制約の違反をキャッチしたいのですが、方法がわかりません。
- RDBMS - MSSQL サーバー 2008
- NHibernate 3.3 のバージョン
NHibernateの構成:
public NHibernate.Cfg.Configuration GetConfiguration()
{
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionSqlServer"].ConnectionString;
var cfg = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(connectionString)
.ShowSql()
.Driver<NHibernate.Driver.Sql2008ClientDriver>()
.Provider<NHibernate.Connection.DriverConnectionProvider>()
.Dialect<NHibernate.Dialect.MsSql2008Dialect>())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<EntityBase>().Conventions.Add(DynamicUpdate.AlwaysTrue()))
.ExposeConfiguration(config =>
{
config.SetInterceptor(new SqlStatementInterceptor());
config.SetProperty(Environment.SqlExceptionConverter,
typeof(MsSqlExceptionConverter).AssemblyQualifiedName);
config.Properties[Environment.CurrentSessionContextClass] = "web";
var schemaUpdate = new SchemaUpdate(config);
schemaUpdate.Execute(false, true);
})
.BuildConfiguration();
return cfg;
}
ISQLExceptionConverterの実装:
public class MsSqlExceptionConverter : ISQLExceptionConverter
{
public Exception Convert(AdoExceptionContextInfo exInfo)
{
var sqle = ADOExceptionHelper.ExtractDbException(exInfo.SqlException) as SqlException;
if (sqle != null)
{
switch (sqle.Number)
{
case 547:
return new ConstraintViolationException(exInfo.Message,
sqle.InnerException, exInfo.Sql, null);
case 208:
return new SQLGrammarException(exInfo.Message,
sqle.InnerException, exInfo.Sql);
case 3960:
return new StaleObjectStateException(exInfo.EntityName, exInfo.EntityId);
}
}
return SQLStateConverter.HandledNonSpecificException(exInfo.SqlException,
exInfo.Message, exInfo.Sql);
}
}
try-catchステートメント:
public void InsertCultures()
{
using (var uow = _unitOfWorkFactory.Create())
{
var CULTURE_DEFAULTS = new List<Culture>()
{
new Culture() {Symbol = "ro-RO", Language = "Romana"},
new Culture() {Symbol = "ru-RU", Language = "Rusa"},
new Culture() {Symbol = "en-US", Language = "Engleza"}
};
foreach (var culture in CULTURE_DEFAULTS)
{
try
{
_cultureRepository.Create(culture);
}
catch (ConstraintViolationException e)
{
}
}
/// Other stuff
}
}
誰かが Eagle-Eye を持っている場合は、共有してください :) ありがとうございます!