启动一个新的 ASP.NET MVC 3 应用程序并收到以下错误:
The primary key value cannot be deleted because references to this key still exist.
如何解决?
模型(EF 代码优先)
public class Journal
{
public int JournalId { get; set; }
public string Name { get; set; }
public virtual List<JournalEntry> JournalEntries { get; set; }
}
public class JournalEntry
{
public int JournalEntryId { get; set; }
public int JournalId { get; set; }
public string Text { get; set; }
}
Controller
//
// POST: /Journal/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Journal journal = db.Journals.Find(id);
db.Journals.Remove(journal);
db.SaveChanges(); // **exception occurs here**
return RedirectToAction("Index");
}
数据库设置
public class FoodJournalEntities : DbContext
{
public DbSet<Journal> Journals { get; set; }
public DbSet<JournalEntry> JournalEntries { get; set; }
}
最佳答案
找到解决方案:
public class FoodJournalEntities : DbContext
{
public DbSet<Journal> Journals { get; set; }
public DbSet<JournalEntry> JournalEntries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Journal>()
.HasOptional(j => j.JournalEntries)
.WithMany()
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
}
关于c# - 如何删除带有外键约束的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9752287/