我正在創建一個ASP.Net MVC 3應用程序,並且在嘗試更新我的數據庫時遇到外鍵約束問題使用遷移。我使用的代碼優先,而我得到的錯誤是:ASP.Net MVC 3 EF「在表中引入FOREIGN KEY約束可能導致循環或多個級聯路徑」
引進國外KEY約束「FK_CategoryItemValues_CategoryProperties_CategoryPropertyId」表「CategoryItemValues」可能會導致循環或多個級聯路徑。指定ON DELETE NO ACTION或ON UPDATE NO ACTION,或修改其他FOREIGN KEY約束。 無法創建約束。查看以前的錯誤。
這裏是我的課:
public class Category
{
public int Id { get; set; }
[Display(Name = "Category Name")]
public string CategoryName { get; set; }
[Display(Name = "Display Name")]
public string DisplayName { get; set; }
[Display(Name = "Display Order")]
public int DisplayOrder { get; set; }
public bool IsTab { get; set; }
public bool Active { get; set; }
public virtual List<CategoryProperty> Properties { get; set; }
}
public class CategoryProperty
{
public int Id { get; set; }
public int CategoryId { get; set; }
[Display(Name="Property Name")]
public string PropertyName { get; set; }
[Display(Name = "Display Order")]
public int DisplayOrder { get; set; }
public virtual Category Category { get; set; }
}
public class CategoryItem
{
public int Id { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public virtual List<CategoryItemValue> Values { get; set; }
}
public class CategoryItemValue
{
public int Id { get; set; }
public int CategoryItemId { get; set; }
public int CategoryPropertyId { get; set; }
public string Value { get; set; }
public virtual CategoryItem Item { get; set; }
public virtual CategoryProperty Property { get; set; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// I know that the solution needs to go here!
}
好像我需要在刪除CategoryItemValues禁用級聯,但我不知道該怎麼做。我知道我需要做的是這樣的:
modelBuilder.Entity < ...>() .HasRequired(...) .WithMany(...) .HasForeignKey(...) .WillCascadeOnDelete (假);
但我不能完全正確。
謝謝!這工作完美。 – MattSavage 2012-04-23 21:53:52
在哪裏寫下部代碼@MattSavage – 2014-08-27 14:48:16
@JotDhaliwal你'DbContext'類實現內,覆蓋'OnModelCreating(DbModelBuilder模型構建器)' - 這是典型的使用,或者你可以每個實體使用EntityTypeConfiguration(有點不同,但類似) – NSGaga 2014-08-27 16:44:38