EF 4.0 - 多对多关系 - 删除问题 [英] EF 4.0 - Many to Many relationship - problem with deletes

查看:110
本文介绍了EF 4.0 - 多对多关系 - 删除问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的实体模型如下:
个人,商店和PersonStores多对多子表来存储PeronId,StoreId
当我在下面的代码中找到一个人,并尝试删除所有StoreLocations,它从PersonStores中删除它们,但也从Store Table中删除它是不合需要的。
另外如果我有另一个拥有相同商店ID的人,那么它就不会说
DELETE语句与REFERENCE约束\FK_PersonStores_StoreLocations\冲突。发生在数据库\EFMapping2\中,表\dbo.PersonStores\,StoreId列。\r\\\
该语句已被终止
,因为它试图删除StoreId,但是StoreId用于另一个PeronId,因此抛出异常。

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();
            }
        } 


推荐答案

问题在于,您实际上并不想删除商店本身,只是商店与该人之间的关系。尝试这样的东西:

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();
 }

这将让您的人员从他的商店列表中删除所有商店,并保存更改。请注意,根据 ObjectContext 的配置,您可能需要在中使用块的第一行添加一个include语句。

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.

这篇关于EF 4.0 - 多对多关系 - 删除问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆