![](/img/trans.png)
[英]How do I delete records before a specified date in Entity Framework Core excluding the latest?
[英]How do I delete a set of records in Entity Framework .Core?
我有一个 EF model(和相应的 MSSQL 表)“HCF”。
我有另一个 EF model(和 MSSQL 表),“HCFNotes”。 没有外键约束或多对一:它们只是两个单独的表。
我有一个删除 HCF 记录的 ASP.Net Core Razor 页面,如下所示:
var HCF = await _context.HCF.FindAsync(id);
_context.HCF.Remove(HCF);
await _context.SaveChangesAsync();
我可以通过这个 LINQ 获得“相关注释”的列表:
IQueryable<HCReportingNote> notesQuery =
from n in _context.HCReportingNotes
where n.HCFId == HCF.ID
select n;
我可以像这样删除原始 SQL 中的所有相关注释:
delete from HCReportingNotes where ID = HCFId
但我更喜欢使用 LINQ。
问: .Select()
列表和 .Remove( .Remove()
或.Clear()
关联注释的“正确”语法是什么?
由于您已经获得了相关注释的列表,因此请在RemoveRange
上使用DbSet
,删除每个元素。 保存更改后可以应用。
//...
var HCF = await _context.HCF.FindAsync(id);
_context.HCF.Remove(HCF);
IQueryable<HCReportingNote> notesQuery =
from n in _context.HCReportingNotes
where n.HCFId == HCF.ID
select n;
_context.HCReportingNotes.RemoveRange(notesQuery);
await _context.SaveChangesAsync();
//...
If you need to delete larger amounts of elements, I would highly recommend this free nuget package that does such things without loading entities into memory: https://entityframework-plus.net/
通过接受的答案,每个元素都将加载到需要删除的 memory 中。
免责声明:我不隶属于 nuget package。 他们确实提供了一个付费版本,可以做更多的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.