Home » C# » EF core 6 – how to remove a many to many relationship

EF core 6 – how to remove a many to many relationship

By Emily

During the development of a .Net Core API recently I was using EF Core 6 and needed to set up a Many To Many relationship. I found plenty of examples for how to create a Many to Many relationship between entities, and how to add a new relationship between the two. However, I found much less info on how to remove an EF Core many to many relationship.

In my particular case there was a table of Users and a table called Teams. The many to many relationship was between Users and Teams. I needed to remove the EF Core many to many relationship between one user and their old team.

I wanted to remove a User from a Team, and to do so I needed to remove the relationship that was defined in the TeamUsers table. I wrote the code that I thought would work – as follows:

var remove = await _context.TeamUsers
                .FIrstOrDefaultAsync(x => x.TeamId == 20 && x.UserId == 5);
            
_context.TeamUsers.Remove(remove);
_context.Save();

… but it didn’t remove the relationship. At that point I googled and found other people reporting the same code didn’t work and I struggled to find the answer.

The code that worked

Eventually I tried using .SingleAsync() instead of FirstOrDefaultAsync() and to my surprise it worked! The working code was as follows:

var remove = await _context.TeamUsers
                .SingleAsync(x => x.TeamId == 20 && x.UserId == 5);
            
_context.TeamUsers.Remove(remove);
_context.Save();

You may like: