添加/删除许多在实体框架许多联想 [英] Add/Remove many to many associations in Entity Framework

查看:94
本文介绍了添加/删除许多在实体框架许多联想的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的示例数据库三个表:

I have three tables in my sample database:

  • ID
  • 用户名
  • 密码
  • ID
  • 名称
  • 说明
  • 用户名
  • RoleID

UserRoles是一个查找表来模拟一个多对多的关系。添加记录到该表允许一个记录用户和角色联系起来。我的问题是,在实体框架是正确的跨$ P $点这是一个多对多的关系和摘要走的查找表。由此产生的实体和关系是这样的:

UserRoles is a lookup table to simulate a many to many relationship. Adding records to this table allows one to associate records in Users and Roles. My problem is that in Entity Framework it correctly interprets this as a many to many relationship and abstracts away that lookup table. The resulting entities and relationship look like this:

这伟大工程的大部分时间,但我不知道做什么,当我想从查找表中添加/删除条目。我可以删除角色或用户,但实际删除的对象不只是与对方的联系。

This works great most of the time, but I'm not sure what to do when I want to add/delete entries from that lookup table. I can delete roles or users but that actually deletes the objects not just their association with each other.

我知道的一个选项,以一个虚拟列添加到UserRoles查找表。这将迫使实体框架打开查找表成一个成熟的实体,让我能够添加和删除它们作为唯一的目标。但我有没有必要为一个虚拟列,这似乎是一个黑客。我在寻找更好的建议。

I do know of one option to add a dummy column to the UserRoles lookup table. That will force Entity Framework to turn the lookup table into a full-blown entity, allowing me to add and remove them as lone objects. But I have no need for a dummy column and this seems like a hack. I am looking for better suggestions.

任何帮助是AP preciated。

Any help is appreciated.

推荐答案

这应该是这个样子:

user.Roles.Remove(existingRoleEntity);

要添加关系

user.Roles.Add(existingRoleEntity);

这篇关于添加/删除许多在实体框架许多联想的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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