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?
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");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With