开始了新的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; }
}
控制器
//
// 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");
}
DB设置
public class FoodJournalEntities : DbContext
{
public DbSet<Journal> Journals { get; set; }
public DbSet<JournalEntry> JournalEntries { get; set; }
}
在数据库中可以为父表选择级联删除选项吗? – Pankaj 2012-03-17 18:04:10
您的答案可能已经[在此](http://stackoverflow.com/a/5522422/60761)。如果不是,请发布DbSetup代码。您可以删除视图。 – 2012-03-17 18:04:40
@PankajGarg - 我确认数据库已经有这个集合。 – 2012-03-17 18:17:01