Remove() 不适用于实体框架中的多对多关系
我正在尝试从实体框架中的集合中删除对象,但不幸的是我的代码失败了。如果您能看一下并让我知道您是否能找出我做错了什么,我将不胜感激。我的对象如下:
- Person <-> Badge (多对多关系)
- Badge <-> BadgeRequirement(一对多关系)
- 人员包含徽章的 ICollection
- 徽章包含人员的 ICollection
- BadgeRequirement 包含徽章 外键
添加和编辑条目效果绝对很好。
但是,当我尝试使用下面的代码从人员中删除徽章时,它不起作用:
Postback event handler on example.aspx
****The person object has been loaded as part of the load event on the page****
Badge badge = BadgeHelper.getBadge(badgeID);
if (command == "Delete")
{
PersonHelper.removeBadgeFromPerson(badge, person);
}
Delete method on PersonHelper class (wrapper for all processing)
person.Badges.Remove(badge);
DbContext.SaveChanges();
Remove(badge) 返回 false,并且我无法对此进行分析,因为我正在使用 SQL Compact 4.0
提前感谢您的帮助!
I am trying to remove an object from a collection in entity framework, but unfortunately my code is failing. I would be grateful if you could have a look and let me know if you can figure out what I'm doing wrong. My objects are as follows:
- Person <-> Badge (many-to-many relationship)
- Badge <-> BadgeRequirement (one-to-many relationship)
- Person contains an ICollection of Badges
- Badge contains an ICollection of Person
- BadgeRequirement contains a Badge Foreign Key
Adding and editing entries works absolutely fine.
However, when I try to remove a Badge from a Person using the code below, it doesn't work:
Postback event handler on example.aspx
****The person object has been loaded as part of the load event on the page****
Badge badge = BadgeHelper.getBadge(badgeID);
if (command == "Delete")
{
PersonHelper.removeBadgeFromPerson(badge, person);
}
Delete method on PersonHelper class (wrapper for all processing)
person.Badges.Remove(badge);
DbContext.SaveChanges();
The Remove(badge) returns false and I cannot profile this as I am using SQL Compact 4.0
Thanks in advance for your help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,这个问题已在 MSDN 论坛之一中得到解决。完整详细信息可以在链接 这里
然而,作为总结,要使用Remove()方法,多对多关系中的两个集合都需要在发生任何更改之前加载。代码示例附在下面:
我希望这可以帮助其他遇到类似问题的人。
This was actually resolved in one of the MSDN forums. The full details can be found on the link here
However, as a summary, to use the Remove() method, both collections in the many to many relationship need to be loaded before any changes take place. The code sample is attached below:
I hope that this helps somebody else with similar issues.
遇到同样的问题,我最终只是对连接表执行原始 SQL 命令:
Had the same issue, I ended up just executing a raw SQL command against the join table: