简体   繁体   English

删除包含DbSet对象的DbSet对象

[英]Delete a DbSet object that has containing DbSet objects

I have coded a C# MVC5 internet application, where I have a MapCompany object that has a List<MapLocation> . 我已经编写了一个C#MVC5 Internet应用程序,其中有一个MapCompany对象,该对象具有List<MapLocation> I have a DbSet<MapCompany> as well as a DbSet<MapLocation> . 我有一个DbSet<MapCompany>以及一个DbSet<MapLocation> When I call the Delete Action result when trying to delete a MapCompany object, I am getting the following error: 当我尝试删除MapCompany对象时调用Delete Action结果时,出现以下错误:

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.MapLocations_dbo.MapCompanies_MapCompany_Id". DELETE语句与REFERENCE约束“ FK_dbo.MapLocations_dbo.MapCompanies_MapCompany_Id”冲突。 The conflict occurred in database "TestDatabase", table "dbo.MapLocations", column 'MapCompany_Id'. 数据库“ TestDatabase”的表“ dbo.MapLocations”的列“ MapCompany_Id”中发生了冲突。
The statement has been terminated. 该语句已终止。

Do I need to remove all the associated MapLocations when removing a MapCompany object? 我是否需要删除所有相关MapLocations删除时MapCompany对象? If so, what is the easiest way to do this? 如果是这样,最简单的方法是什么? Is there an easier/better way rather than looping through each object, and removing each object manually? 是否有比循环遍历每个对象并手动删除每个对象更简单/更好的方法? Also, at a future stage, each MapLocation will have many MapLocationItem objects. 而且,在将来的阶段,每个MapLocation将具有许多MapLocationItem对象。

Manual 手册

Delete the items manually. 手动删除项目。 This is sometimes the preferred option as it gives you full control. 有时这是首选方法,因为它可以让您完全控制。

Cascaded Deletes 级联删除

You can set the foreign key relationship to cascade deletes. 您可以将外键关系设置为级联删除。 This means that deleting the parent record will delete all records from the table that references it. 这意味着删除父记录将从引用它的表中删除所有记录。 To enable cascaded deletes on a table, read this answer . 要在表上启用级联删除,请阅读此答案

Alternatively if you are using code first development, you can enable cascading deletes using the fluent API: 或者,如果您正在使用代码优先开发,则可以使用fluent API启用级联删除:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<MapCompany>()
        .HasOptional(a => a.MapLocations)
        .WithOptionalDependent()
        .WillCascadeOnDelete(true);
}

Here is a good discussion on the pros/cons of cascaded deletes: What are the Pros and Cons of Cascading delete and updates? 这是有关级联删除的优点/缺点的很好的讨论: 级联删除和更新的优点和缺点是什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM