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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9752287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 08:42:45  来源:igfitidea点击:

How to delete a record with a foreign key constraint?

c#asp.netasp.net-mvcentity-frameworkentity-framework-4.1

提问by O.O

Started a new ASP.NET MVC 3 application and getting the following error:

启动一个新的 ASP.NET MVC 3 应用程序并收到以下错误:

The primary key value cannot be deleted because references to this key still exist.

无法删除主键值,因为对该键的引用仍然存在。

How to solve this?

如何解决这个问题?

Models (EF code-first)

模型(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");
}

DB Setup

数据库设置

public class FoodJournalEntities : DbContext
{
    public DbSet<Journal> Journals { get; set; }
    public DbSet<JournalEntry> JournalEntries { get; set; }
}

采纳答案by O.O

Found the solution:

找到了解决办法:

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

来源

回答by Owais Qureshi

If you delete a record from a table(lets say "blah"), which has other relationships with other tables (xyz,abc). By default, the database will prevent you from deleting a row in "blah" if there are related rows in one of the other tables.
Solution #1:
You can manually delete the related rows first,this may require a lot of work.
Solution #2:
an easy solution is to configure the database to delete them automatically when you delete a "blah" row.

如果您从表中删除一条记录(可以说“等等”),它与其他表(xyz,abc)有其他关系。默认情况下,如果其他表之一中有相关行,数据库将阻止您删除“blah”中的行。
解决方案#1:
您可以先手动删除相关行,这可能需要大量工作。
解决方案#2:
一个简单的解决方案是将数据库配置为在删除“blah”行时自动删除它们。

Follow this open your Database diagram,and click on the properties on the relationship

按照这个打开你的数据库图,然后点击关系上的属性

enter image description here

在此处输入图片说明

In the Properties window, expand INSERTand UPDATESpecification and set the DeleteRuleproperty to Cascade.
enter image description here

在 Properties 窗口中,展开INSERTUPDATESpecification 并将DeleteRule属性设置为 Cascade。
在此处输入图片说明

Save and close the diagram. If you're asked whether you want to update the database, click Yes.

保存并关闭图表。如果系统询问您是否要更新数据库,请单击是。

To make sure that the model keeps entities that are in memory in sync with what the database is doing, you must set corresponding rules in the data model. Open SchoolModel.edmx, right-click the association line between "blah" and "xyz", and then select Properties.

为了确保模型使内存中的实体与数据库正在执行的操作保持同步,您必须在数据模型中设置相应的规则。打开 SchoolModel.edmx,右键单击“blah”和“xyz”之间的关联线,然后选择“属性”。

In the Properties window, expand INSERTand UPDATESpecification and set the DeleteRuleproperty to Cascade.

在 Properties 窗口中,展开INSERTUPDATESpecification 并将DeleteRule属性设置为 Cascade。

Solution and images taken from http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-2

解决方案和图片取自http://www.asp.net/web-forms/tutorials/getting-started-with-ef/the-entity-framework-and-aspnet-getting-started-part-2

回答by Hasnain Mehmood

I found it...

我找到了...

Go TO SQL Server

转到 SQL Server

Make his Database diagrammed

使他的数据库图表化

Right click on relation ship line between parent and child and open the property of it.

右击父子关系线,打开它的属性。

Set INSERT And Update Specification and simply set DELETE RULE TO CASCADE.

设置 INSERT And Update Specification 并简单地设置 DELETE RULE TO CASCADE。

Remember No code is required in Project FOR this PURPOSE and simply debug and enjoy it.

请记住,为此目的在项目中不需要任何代码,只需调试并享受它。