【问题标题】:How to delete all related entities from database with Entity Framework code-first如何使用实体框架代码优先从数据库中删除所有相关实体
【发布时间】:2020-06-22 15:55:46
【问题描述】:

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

    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-framework code-first


    【解决方案1】:

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

    详情请看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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 1970-01-01
      相关资源
      最近更新 更多