首页 > 解决方案 > 如何使用实体框架代码优先从数据库中删除所有相关实体

问题描述

我在删除相关实体时遇到问题。例如,我需要从用户系列集合中删除其中一个系列。发生这种情况时,我希望删除数据库中与该系列记录相关的所有内容。怎么做?请提供示例,我有点卡住了。谢谢!

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

标签: c#entity-frameworkcode-first

解决方案


您实际上是在寻找级联删除。

详情请看 https://www.entityframeworktutorial.net/code-first/cascade-delete-in-code-first.aspx

这是一个例子

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

下面的例子演示了级联删除操作

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

推荐阅读