c# - Entity Framework Core,从嵌套集合中删除项目
问题描述
我有两节课
public class InvoiceRow
{
public int Id { get; set; }
public int InvoiceId { get; set; }
public int ProductId { get; set; }
public virtual Product Product { get; set; }
public int Amount { get; set; }
}
public class Invoice
{
public int Id { get; set; }
private ICollection<InvoiceRow> _rows;
public virtual ICollection<InvoiceRow> Rows => _rows ?? (_rows = new List<InvoiceRow>());
}
我在存储库类中使用更新方法
public void Update(Invoice record)
{
dB.Invoices.Update(record);
dB.SaveChanges();
}
它适用于更新行集合中的值并添加新行,但是如果我传递的对象的行数少于数据库中的行数,它不会删除项目。最好的方法是什么?
解决方案
那是因为数据库中的行没有被标记为删除。
仅更新新的或更改的项目。集合中的“缺失”项目不被视为已删除。
因此,您需要自己标记要删除的项目。像这样的东西:
public void Update(Invoice record)
{
var missingRows = dB.InvoiceRows.Where(i => i.InvoiceId == record.Id)
.Except(record.Rows);
dB.InvoiceRows.RemoveRange(missingRows);
dB.Invoices.Update(record);
dB.SaveChanges();
}
推荐阅读
- sql - 是否可以在 Microsoft Access 中为表格单元格添加格式?
- c++ - 更新 CMake(似乎已经)破坏了我的程序
- javascript - 如何使用 emailjs 将电子邮件发送到收件箱,每次电子邮件登陆到垃圾邮件
- java - 使用 JNDI 和 Hibernate 配置 Spring
- tensorflow - tf.multinomial 输出数字范围以外的数字
- c# - Visual Studio Forms:有时,选择数据网格单元格不会将单元格的 Selected 属性设置为 true?
- jquery - 为什么在这种情况下 toggleClass 不起作用?
- unreal-engine4 - 虚幻引擎 - 手电筒在 180 度旋转时变暗
- aes - 一个h.264派生流协议的询问
- python - 使用列表格式的数据创建查询