9

次の 2 つのエンティティがあるとします。

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 が発生したときに、これが dont cascade レコードの削除に関連していることを確認するためのエラー コードはありますか? SQLサーバーがエラー番号547を返すことは知っていますが、エンティティフレームワークはどうですか?

4

1 に答える 1

23

SqlExceptionEntity 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");
        }
    }
}
于 2013-05-02T21:27:12.293 に答える