Entity Framework Core,从嵌套集合中删除项目

编程入门 行业动态 更新时间:2024-10-27 09:33:01
本文介绍了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>()); }

我在存储库类中使用 Update 方法

I use Update method in the repository class

public void Update(Invoice record) { dB.Invoices.Update(record); dB.SaveChanges(); }

它适用于更新行集合中的值并添加新行,但是它不会删除项目,如果我传递的对象行数少于数据库中的行数.最好的方法是什么?

It works for updating values in the collection of rows and adding new rows as well, however it doesn't remove items, if I pass object with less rows than it has in the database. What is the best approach to do it?

推荐答案

那是因为数据库中的行没有被标记为删除.

That is because the rows in the database are not marked for deletion.

仅更新新的或更改的项目.集合中丢失"的项目不被视为被删除.

Only new or changed items are updated. 'Missing' items from a collection are not considered to be deleted.

所以您需要做的是自己标记要删除的项目.像这样:

So what you'll need to do is mark the items for deletion yourself. Something like this:

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

更多推荐

Entity Framework Core,从嵌套集合中删除项目

本文发布于:2023-11-14 03:12:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1586060.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   项目   Entity   Framework   Core

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!