Search code examples
c#entity-frameworkcode-first

How to delete all related entities from database with Entity Framework code-first


I have a problem with related entities deletion. For example, I need to delete one of series from user series collection. When this happens I want all of related to this series records in database to be deleted. How to do it? Please provide example, I'm stuck a little. Thank you!

    public class User
    {
        public Guid UserId { get; set; }
        public virtual List<Series> UserSeries { get; set; }
    }

    public class DropPhoto
    {
        public Guid DropPhotoId { get; set; }

        public virtual SimpleLine SimpleHorizontalLine { get; set; }
        public virtual SimpleLine SimpleVerticalLine { get; set; }
        public virtual Drop Drop { get; set; }
    }

    public class ReferencePhoto
    {
        public Guid ReferencePhotoId { get; set; }
        public virtual SimpleLine SimpleLine { get; set; }
    }

    public class Series
    {
        public Guid SeriesId { get; set; }
        public virtual List<DropPhoto> DropPhotosSeries { get; set; }
        public virtual ReferencePhoto ReferencePhotoForSeries { get; set; }          
    }

    public class SimpleLine
    {
        public Guid SimpleLineId { get; set; }
    }

public class Drop
{
    public Guid DropId { get; set; }
}

Solution

  • You are actually looking for cascade delete.

    For details please look at https://www.entityframeworktutorial.net/code-first/cascade-delete-in-code-first.aspx

    Here is an example

        public class Student
    {
        public int StudentId { get; set; }
        public string StudentName { get; set; }
    
        public virtual StudentAddress Address { get; set; }
    }
    
    public class StudentAddress 
    {
        [ForeignKey("Student")]
        public int StudentAddressId { get; set; }
        public string Address1 { get; set; }
        public string Address2 { get; set; }
        public string City { get; set; }
        public int Zipcode { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
    
        public virtual Student Student { get; set; }
    }
    

    The following example demonstrates the cascade delete operation

    using (var ctx = new SchoolContext()) 
    {
        var stud = new Student() { StudentName = "James" };
        var add = new StudentAddress() { Address1 = "address" };
    
        stud.Address = add;
    
        ctx.Students.Add(stud);
    
        ctx.SaveChanges();
    
        ctx.Students.Remove(stud);// student and its address will be removed from db
    
        ctx.SaveChanges();
    }