尝试删除非级联实体时EF中的异常处理

时间:2013-05-02 20:44:15

标签: entity-framework ef-code-first

假设有两个实体:

public class Category
{
    public string Id { get; set; }
    public string Caption { get; set; }
    public string Description { get; set; }

    public virtual IList<Product> Products { get; set; }
}

public class Product
{
    public string Id { get; set; }
    public string CategoryId { get; set; }
    public string Caption { get; set; }
    public string Description { get; set; }

    public virtual Category Category { get; set; }
}

并且不允许级联删除。

public class ProductMap : EntityTypeConfiguration<Product>
{
    public ProductMap()
    {
        // Primary Key
        this.HasKey(t => t.Id);

        // Properties
        this.Property(t => t.Caption)
            .IsRequired()
            .HasMaxLength(50);

        // Table & Column Mappings
        this.ToTable("Products");
        this.Property(t => t.Id).HasColumnName("Id");
        this.Property(t => t.Caption).HasColumnName("Caption");

        // Relationships
        this.HasRequired(t => t.Category)
            .WithMany(t => t.Products)
            .HasForeignKey(d => d.CategoryId)
            .WillCascadeOnDelete(false);
    }
}

所以当我想删除某些与之相关的产品的类别时,会产生DbUpdateException。并在异常写入的错误消息中:

{"The DELETE statement conflicted with the REFERENCE constraint \"FK_dbo.Products_dbo.Categories_CategoryId\". The conflict occurred in database \"TestDb\", table \"dbo.Products\", column 'CategoryId'.\r\nThe statement has been terminated."}

有任何错误代码可以找出当被认为是DbUpdateException时这与删除不级联记录有关吗? 我知道sql server返回错误号547但实体框架呢?

1 个答案:

答案 0 :(得分:16)

您可以获取导致实体框架特定异常的原始SqlException

包含各种有用信息,例如包含Sql Server错误代码的Number属性。

这应该可以解决问题:

try
{
    tc.SaveChanges();
}
catch (DbUpdateException ex)
{
    var sqlException = ex.GetBaseException() as SqlException;

    if (sqlException != null)
    {
        var number = sqlException.Number;

        if (number == 547)
        {
            Console.WriteLine("Must delete products before deleting category");
        }
    }
}