Bắt đầu một ứng dụng ASP.NET MVC 3 mới và nhận được lỗi sau:Làm cách nào để xóa bản ghi có ràng buộc khóa ngoài?
The primary key value cannot be deleted because references to this key still exist.
Làm thế nào để giải quyết này?
Models (EF mã đầu tiên)
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; }
}
khiển
//
// 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 Cài đặt
public class FoodJournalEntities : DbContext
{
public DbSet<Journal> Journals { get; set; }
public DbSet<JournalEntry> JournalEntries { get; set; }
}
Trong cơ sở dữ liệu, bạn có thể chọn tùy chọn xóa tầng cho bảng cha của bạn không? – Pankaj
Câu trả lời của bạn có thể [ở đây] (http://stackoverflow.com/a/5522422/60761) rồi. Nếu không, hãy đăng mã DbSetup. Bạn có thể xóa Chế độ xem. –
@PankajGarg - Tôi đã xác minh cơ sở dữ liệu đã có bộ này. –