如何处理UpdateException?

Med*_*tor 4 c# entity-framework-4 updateexception

我需要处理异常重复.

var resource = new Resource() { url = tbUrl.Text };
try
{
    context.Resource.AddObject(resource);
    context.SaveChanges();
}   
catch(UpdateException ex)
{
    // how to know exactly which is why the error occurred
}
catch (Exception ex)
{

    throw;
}
Run Code Online (Sandbox Code Playgroud)

更新:

我需要捕获当我尝试不添加唯一值时发生的错误.UpdateException - 在添加数据时出错.

Jul*_*tow 6

这可能有点晚,但对于任何查找详细信息的ASP.NET数据库更新错误的人来说,InnerException错误处理程序非常有用且详细.

        try { 

            db.SaveChanges();                              
        }

        catch (System.Data.UpdateException ex)    
        {
            Console.WriteLine(ex.InnerException);
        }


        catch (System.Data.Entity.Infrastructure.DbUpdateException ex) //DbContext
        {
            Console.WriteLine(ex.InnerException);
        }

        catch (Exception ex)
        {

            Console.WriteLine(ex.InnerException);
            throw;
        }
Run Code Online (Sandbox Code Playgroud)

数据库中的T-SQL阻止插入重复的城市.

USE [ModelFirstApplication]
GO

/****** Object:  Index [UQ_Address_City]    Script Date: 5/30/2012 7:26:16 AM ******/
ALTER TABLE [dbo].[Addresses] ADD  CONSTRAINT [UQ_Address_City] UNIQUE NONCLUSTERED 
([City] ASC)
GO
Run Code Online (Sandbox Code Playgroud)

因此,如果用户尝试将"Spokane"第二次插入到此演示应用程序的Addresses表中,则上述异常处理程序报告

System.Data.UpdateException: An error occurred while updating the entries. 

See the inner exception for details. ---> 

System.Data.SqlClient.SqlException: Violation of UNIQUE KEY constraint 'UQ_Address_City'. 
Cannot insert duplicate key in object 'dbo.Addresses'. 
The duplicate key value is (Spokane).
The statement has been terminated.
Run Code Online (Sandbox Code Playgroud)

知道要使用哪个异常处理程序非常方便,你的问题很清楚.