我是EF的新手并尝试使用Code First设计我的数据库。以下是我的三个实体(我没有写过所有属性)。我有一个颂歌的情况。管理员不允许编辑费用,因此我必须创建另一个实体(EditedExpense)以在另一个表中包含所有已编辑的费用。因此,当管理员尝试更改(编辑)费用并单击“保存”时,将创建EditedExpense中的新帖子。
public class Expense
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int ExpenseId { get; set; }
[Required]
public int CategoryId{ get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
public virtual List<EditedExpense> EditedExpenses { get; set; }
}
public class EditedExpense
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int EditedExpenseId { get; set; }
[Required]
public int CategoryId{ get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
public int ExpenseId { get; set; }
}
public class Category
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int CategoryId{ get; set; }
public string Title
public virtual List<Expense> Expenses { get; set; }
public virtual List<EditedExpense> EditedExpenses { get; set; }
}
它会生成此错误Introducing FOREIGN KEY constraint 'Expense_EditedExpenses' on table 'EditedExpense' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints
答案 0 :(得分:1)
您需要关闭Category
实体上EditedExpenses
或Expense
上的级联删除。
public class YourDbContext : DbContext
{
// other code ommitted
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// Remove cascade delete from Category.
modelBuilder.Entity<Expense>()
.HasRequired(e => e.Category)
.WithMany(c => c.Expenses)
.WillCascadeOnDelete(false);
// Or remove cascade delete from Edited Expense.
//modelBuilder.Entity<Expense>()
// .HasMany(e => e.EditedExpenses)
// .WithRequired()
// .WillCascadeOnDelete(false);
}
}
以下是the explanation为什么不允许多级联。