最有可能的是,我目前无法对其进行测试,内部异常DbUpdateException
可能是关于重复或外键约束的异常。更重要的是,您有机会通过检查一个国家/地区是否已经存在来不抛出任何异常。我能想到的两种方法是;通过执行简单的选择检查并查看该国家/地区是否已经存在,如果不存在,则执行插入/添加或编写存储过程,然后执行选择/插入或合并并返回您想要返回的任何值.
更新
(这是演示事件逻辑流程的示例代码,不是良好的编程习惯,特别是通过捕获所有异常)
异常逻辑
public AddCountry(string countryTitle)
{
using (var db = new DbContext(_connectionString)
{
try
{
// Linq to (SQL/EF)-ish code
Country country = new Country();
country.ID = Guid.NewGuid();
country.Title = countryTitle;
db.Countrys.Add(country);
db.SubmitChanges(); // <--- at this point a country could already exist
}
catch (DbUpdateException ex)
{
// <--- at this point a country could be delete by another user
throw Exception("Country with that name already exists");
}
}
}
非异常逻辑
public AddCountry(string countryTitle)
{
using (var db = new DbContext(_connectionString)
{
using (TransactionScope transaction = new TransactionScope())
{
try
{
Country country = db.Countries
.FirstOrDefault(x => x.Title = countryTitle);
if (country == null)
{
country = new Country();
country.ID = Guid.NewGuid();
country.Title = countryTitle;
db.Countrys.Add(country);
db.SubmitChanges(); // <--- at this point a country
// shouldn't exist due to the transaction
// although someone with more expertise
// on transactions with entity framework
// would show how to use transactions properly
}
}
catch (<someTimeOfTransactionException> ex)
{
// <--- at this point a country with the same name
// should not exist due to the transaction
// this should really only be a deadlock exception
// or an exception outside the scope of the question
// (like connection to sql lost, etc)
throw Exception("Deadlock exception, cannot create country.");
}
}
}
}
很可能需要正确配置 TransactionScope(Transaction transactionToUse) 构造函数。可能将 Transactions.IsolationLevel 设置为 Serializable
我还建议阅读Entity Framework transaction。