Removing attached object (1..n relation) in the Entity Framework

Posted by

When having 1…n relation between a base object and a list of other object, e.g. when a tournament has a list of players, removing one of the players from the list isn’t as obvious as one might expect.

var t = DB.Tournament.FirstOrDefault(c => c.Id == idTournament);
var g = DB.Golfer.FirstOrDefault(x => x.Id == idGolfer);
t.Golfer.Attach(g);
t.Golfer.Remove(g);
DB.SaveChanges();

This Stack Overflow post fixed this issuse for me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s