开发者

EF 4.0 - Many to Many relationship - problem with deletes

开发者 https://www.devze.com 2022-12-28 20:19 出处:网络
My Entity Model is as follows: Person , Store and PersonStores Many-to-many child table to store PeronId,StoreId

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 confli开发者_如何学Pythoncted 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();
            }
        } 


The problem is that you don't actually want to delete the store itself, just the relation between the store and the person. Try something like this instead:

 Person p = null;
 using (ClassLibrary1.Entities context = new ClassLibrary1.Entities())
 {
     p = context.People.Where(x=> x.PersonId == 11).FirstOrDefault();
     p.StoreLocations.Clear();
     context.SaveChanges();
 }

That will get your person, remove all the stores from his list of stores, and save the changes. Note that you might need an include statement on the first row in the using block, depending on how your ObjectContext is configured.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号