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

Pez*_*aee 7 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; }
}
Run Code Online (Sandbox Code Playgroud)

并且不允许级联删除.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

所以,当我想删除某些与之相关的产品的类别时,会产生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."}
Run Code Online (Sandbox Code Playgroud)

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

Pet*_*sen 17

您可以获取SqlException导致Entity Framework特定异常的原因.

那个包含各种有用的信息,比如Number包含Sql Server错误代码的属性.

这应该做的伎俩:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)