mercredi 26 septembre 2012

How to delete many-to-many relationship in Entity Framework...

Hi Folks,

I've been searching the internet to find a simple way to delete a many-to-many relationship item using Entity Framework Code-First...

I couldn't find something very useful so I have written  my own code.

The problem is if you try to use a foreach statement you'll be able to delete the first item but not the others, as the collection would be modified.

So I made the following assumption: Two tables, the first is Contenu and the second Tag, with a many-to-many relationship in SQL Server, I called the table ContenuTag, but this table won't appear in our model (this is a normal behaviour).

So here's the code:

var contenu = db.Contenu.Where(c => c.IdContenu == idContenu).FirstOrDefault();
for (int i = 0; i< contenu.Tag.Count(); i++)
{
var tag = contenu.Tag.FirstOrDefault();

contenu.Tag.Remove(tag);               

db.SaveChanges();

}
 

Simple, yeah?

Hope this helps,

Raphaël