gpt4 book ai didi

c# - 如何使用 Entity Framework 代码优先从数据库中删除所有相关实体

转载 作者:行者123 更新时间:2023-12-02 07:49:09 25 4
gpt4 key购买 nike

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

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

最佳答案

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

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

关于c# - 如何使用 Entity Framework 代码优先从数据库中删除所有相关实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60622929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com