Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
}
like image 265
Fallingsappy Avatar asked Dec 06 '25 20:12

Fallingsappy


1 Answers

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();
}
like image 82
ATHER Avatar answered Dec 08 '25 10:12

ATHER



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!