c# - 如何删除带有外键约束的记录?

标签 c# asp.net asp.net-mvc entity-framework entity-framework-4.1

启动一个新的 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);
    }
}

Source

关于c# - 如何删除带有外键约束的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9752287/

相关文章:

asp.net - 版面无法在asp.net Core 3.0的使用者设定档上使用

c# - 使用正则表达式在 svg 文件中查找替换为 '(' 和 ')' 字符的文本

asp.net-mvc - 尝试使用 SignalR 检测浏览器关闭事件

c# - 使用 protobuf-net 反序列化未知类型

c# - 简单地在 C# 中比较两个对象的属性

c# - 为什么 LINQ Sum() 抛出 "System.Collections.Generic.KeyNotFoundException"?

c# - 在 MySql.Data.EntityFrameworkCore 中找不到 Database SetInitializer

asp.net-mvc - 查找 System.Web.Mvc

c# - 将 TreeView on click 事件执行到另一个 click 事件中

c# - Windows 服务中的 Kerberos 身份验证