3

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?

0

2 Answers 2

3

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

//...
Sign up to request clarification or add additional context in comments.

1 Comment

_context.HCReportingNotes.RemoveRange(notesQuery);: Perfect! Exactly what I was looking for!
2

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.

1 Comment

Thank you for the suggestion. In this case, the #/associated records is small (probably only one or two; seldom more than 10) and the records themselves are tiny. So it's not an issue, either from a "memory" or a "performance" standpoint.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.