Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling in EF when Try To Delete Not Cascaded Entity

assume that there are two entity:

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; }
}

and the cascade delete are not allowed.

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);
    }
}

so when i want to delete a category that some products related to it, and DbUpdateException accurred. and in error message of exception write :

{"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."}

there are any error code to find out that when accurred DbUpdateException this is related to deleting dont cascade records? i know sql server return error number 547 but what about entity framework?

like image 701
Pezhman Parsaee Avatar asked May 02 '13 20:05

Pezhman Parsaee


1 Answers

You can get the original SqlException that is the cause of the Entity Framework specific exception.

That one contains all sorts of useful information, like the Number property containing the Sql Server error code.

This should do the trick:

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");
        }
    }
}
like image 173
Peter Hansen Avatar answered Sep 20 '22 13:09

Peter Hansen