Search code examples
c#entity-frameworkcode-first

How do I delete related objects in Entity framework code first database?


DBContext class is

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

And model looks like:

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; }
    }

Repository class:

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

Entity Framework creates database with two tables: Planets and Buildings, related by Planet_Id field. When I call RemovePlanets() method of my VGDBRepository class it removes planets record from Planets table and sets Planet_Id field of all buildings, related with deleted planets, in Buildings table to null but not deletes them, so I have redundant records in database. I use code-first strategy to create database. How can I force Entity Framework to remove such type of related data???


Solution

  • You would need to cascade your deletes.

    Take a look at this: Stackoverflow Example Cascade Deletes

    And this: Msdn Code First with Enabling Cascade Deletes