c# - 如何删除 Entity Framework 代码优先数据库中的相关对象?

标签 c# entity-framework code-first

DBContext 类是

public class VGDB : DbContext
    {        
        public DbSet<Planet> Planets { get; set; }
    }

模型看起来像:

public class Planet
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }

        ...

        public List<Building> Constructions { get; set; } 
    }


public class Building
    {
        [Key]
        public int Id { get; set; }
        public decimal Lvl { get; set; }
        public string Type { get; set; }
    }

存储库类:

public class VGDBRepository
    {
        private readonly VGDB _vgdb;
        ...
        public void RemovePlanets()
        {
            foreach (Planet planet in _vgdb.Planets)
            {
                _vgdb.Planets.Remove(planet);
            }
            _vgdb.SaveChanges();
        }
        ...
    }

Entity Framework 使用两个表创建数据库:PlanetsBuildings,通过 Planet_Id 字段关联。当我调用 VGDBRepository 类的 RemovePlanets() 方法时,它会从 Planets 表中删除行星记录并设置所有建筑物的 Planet_Id 字段,与已删除相关行星,在建筑物表中为空但不删除它们,所以我在数据库中有冗余记录。我使用 code-first 策略来创建数据库。我如何强制 Entity Framework 删除此类相关数据???

最佳答案

您需要级联删除。

看看这个: Stackoverflow Example Cascade Deletes

还有这个: Msdn Code First with Enabling Cascade Deletes

关于c# - 如何删除 Entity Framework 代码优先数据库中的相关对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11654398/

相关文章:

C# 识别 for 循环中的项目

.net - DbContext ChangeTracker : Id of Added Entity for Auditing

entity-framework - 具有所需关联的 Entity Framework 4.3

c# - 在 Code First MVC 应用程序中查询 AspNet Identity 表

c# - 如何从 asp :checkbox .net c# 中检索多个选定值

c# - 单元测试 "No Symbol loaded"快把我逼疯了

c# - Uncaught ReferenceError :False is not defined

c# - 如何在单元测试中使用 Moq 和 DbFunctions 来防止 NotSupportedException?

c# - IQueryable 与 AlphaNumeric 排序

c# - Entity Framework Code First 是否支持存储过程?