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

Viewed 1458

I have an EF model (and corresponding MSSQL table) "HCF".

I have another EF model (and MSSQL table), "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:

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:

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:

delete from HCReportingNotes where ID = HCFId

But I'd prefer to use LINQ.

Q: What's the "correct" syntax to .Select() the list and .Remove() or .Clear() the associated notes?

2 Answers

Since you have already gotten the list of associated notes, then use RemoveRange on the DbSet, removing each element. 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/

With the accepted answer every element will be loaded into memory that needs to be deleted.

Disclaimer: I am not affiliated with the nuget package. They do offer a paid version that does even more stuff.

Related