4
假設有兩個實體:異常處理EF時嘗試刪除不級聯實體
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."}
有任何錯誤代碼,找出accurred DbUpdateException時,這是關係到刪除不級聯記錄? 我知道sql服務器返回錯誤號547,但實體框架呢?
什麼實體是你應用流暢API來?什麼是'這個'?你是先使用Code First,Model First還是Database? – Justin 2013-05-02 20:51:35
@Justin,請再次查看這篇文章,我現在編輯帖子,我先使用代碼 – 2013-05-02 20:56:08