EF 4.0 - Many to Many relationship - problem with deletes
Posted
by chugh97
on Stack Overflow
See other posts from Stack Overflow
or by chugh97
Published on 2010-04-29T14:47:10Z
Indexed on
2010/04/29
14:57 UTC
Read the original article
Hit count: 523
My Entity Model is as follows:
Person , Store and PersonStores Many-to-many child table to store PeronId,StoreId
When I get a person as in the code below, and try to delete all the StoreLocations, it deletes them from PersonStores as mentioned but also deletes it from the Store Table which is undesirable.
Also if I have another person who has the same store Id, then it fails saying
"The DELETE statement conflicted with the REFERENCE constraint \"FK_PersonStores_StoreLocations\". The conflict occurred in database \"EFMapping2\", table \"dbo.PersonStores\", column 'StoreId'.\r\nThe statement has been terminated"
as it was trying to delete the StoreId but that StoreId was used for another PeronId and hence exception thrown.
Person p = null;
using (ClassLibrary1.Entities context = new ClassLibrary1.Entities())
{
p = context.People.Where(x=> x.PersonId == 11).FirstOrDefault();
List<StoreLocation> locations = p.StoreLocations.ToList();
foreach (var item in locations)
{
context.Attach(item);
context.DeleteObject(item);
context.SaveChanges();
}
}
© Stack Overflow or respective owner