Search code examples
c#sql-serverentity-framework-coreef-code-first

How to set foreign key value to Null when deleting a child record EF Core


I am quite new to Entity Framework and I have an API that can delete records from a SQL Server database, I have the child table ResidenceType and can delete a row using the ID, I have the parent table PropertyGroups with a foreign key ResidenceTypeId. Is there a way I can set the foreign key's value to NULL when I delete a row in ResidenceType that is linked?

Residence Type Table

Residence Type Data

Property Groups Table

Property Groups Data

So the behaviour I need is that if I delete ID 1 from the ResidenceType table, I need EF Core to set the ResidenceTypeId column in PropertyGroups to NULL (or empty). I have tried overriding the OnModelCreating method in my DataContext class but not having much luck, any advice or help would be appreciated.


Solution

  • Turns out I had set everything up correctly I just needed to add the Include clause in the delete method.

    var residenceType = await _context.ResidenceTypes.Include(p => p.PropertyGroups).FirstOrDefaultAsync(i => i.PropertyGroupName == name);
    

    Adding this sets the relevant Id column to null, thanks to the people that tried to help.