9

假设有两个实体:

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 但是实体框架呢?

4

1 回答 1

23

您可以获得SqlException导致实体框架特定异常的原始文件。

那个包含各种有用的信息,比如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");
        }
    }
}
于 2013-05-02T21:27:12.293 回答