如何使用实体框架代码优先从数据库中删除所有相关实体
Posted
技术标签:
【中文标题】如何使用实体框架代码优先从数据库中删除所有相关实体【英文标题】: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;
【问题讨论】:
【参考方案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();
【讨论】:
以上是关于如何使用实体框架代码优先从数据库中删除所有相关实体的主要内容,如果未能解决你的问题,请参考以下文章
EF 代码优先:如何在遵循 DDD 时从实体的集合中删除一行?