简体   繁体   English

如何删除 Entity Framework.Core 中的一组记录?

[英]How do I delete a set of records in Entity Framework .Core?

I have an EF model (and corresponding MSSQL table) "HCF".我有一个 EF model(和相应的 MSSQL 表)“HCF”。

I have another EF model (and MSSQL table), "HCFNotes".我有另一个 EF model(和 MSSQL 表),“HCFNotes”。 There's no foreign key constraint or ManyToOne: they're just two separate tables.没有外键约束或多对一:它们只是两个单独的表。

I have an ASP.Net Core Razor page that deletes the HCF record like this:我有一个删除 HCF 记录的 ASP.Net Core Razor 页面,如下所示:

var HCF = await _context.HCF.FindAsync(id);
_context.HCF.Remove(HCF);
await _context.SaveChangesAsync();

I can get a list of the "associated notes" with this LINQ:我可以通过这个 LINQ 获得“相关注释”的列表:

IQueryable<HCReportingNote> notesQuery =
    from n in _context.HCReportingNotes 
    where n.HCFId == HCF.ID
    select n;

I can delete all the associated notes in raw SQL like this:我可以像这样删除原始 SQL 中的所有相关注释:

delete from HCReportingNotes where ID = HCFId

But I'd prefer to use LINQ.但我更喜欢使用 LINQ。

Q: What's the "correct" syntax to .Select() the list and .Remove() or .Clear() the associated notes?问: .Select()列表和 .Remove( .Remove().Clear()关联注释的“正确”语法是什么?

Since you have already gotten the list of associated notes, then use RemoveRange on the DbSet , removing each element.由于您已经获得了相关注释的列表,因此请在RemoveRange上使用DbSet ,删除每个元素。 Save changes can be applied after.保存更改后可以应用。

//...

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/ 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/

With the accepted answer every element will be loaded into memory that needs to be deleted.通过接受的答案,每个元素都将加载到需要删除的 memory 中。

Disclaimer: I am not affiliated with the nuget package.免责声明:我不隶属于 nuget package。 They do offer a paid version that does even more stuff.他们确实提供了一个付费版本,可以做更多的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM