假设有两个实体:
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 但是实体框架呢?