c# - 如何使用实体框架代码优先从数据库中删除所有相关实体
问题描述
我在删除相关实体时遇到问题。例如,我需要从用户系列集合中删除其中一个系列。发生这种情况时,我希望删除数据库中与该系列记录相关的所有内容。怎么做?请提供示例,我有点卡住了。谢谢!
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();
}
推荐阅读
- url - 在 Postman 中将文件路径作为参数传递
- xaml - 可以更改 UWP 拖放 (DragUI) 标题的字体吗?
- rust - 在 Rust 中按值传递数组
- html - VBA:在 Outlook 电子邮件中嵌入 PNG - 为自己工作而不为他人显示
- spring-boot - 禁用 Spring Security 导致无法加载应用程序上下文
- javascript - 当 scrollY 等于 0.52 时动画 - Next.js ( 使用 framer-motion )
- node.js - 使用 app.js (express) 运行 NestJS 应用程序
- node.js - 如何使用 AWS Lambda (nodeJS) 查询 AWS 外部的 MySQL 数据库?
- rust - std::thread::JoinHandle::join 如何捕捉恐慌?
- c++ - 以某种方式读取文件中的数据