-2

我有一个名为国家的表,我通过在 sql servwer 2008 r2 上创建类型为“唯一键”的“索引/键”来将 country_name 字段定义为唯一的。但目前如果用户插入我的 asp.net mvc3 应用程序中已经存在的 country_name 值,则会引发类型为“System.Data.Entity.Infrastructure.DbUpdateException”的异常,这是非常普遍的。

那么有没有办法在违反唯一约束的情况下定义特定的异常???而不仅仅是引发一般的“System.Data.Entity.Infrastructure.DbUpdateException”异常?

BR

4

1 回答 1

2

最有可能的是,我目前无法对其进行测试,内部异常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

于 2012-04-21T02:30:26.820 回答