If I a many-to-many relationship between Users and Roles and I have an instance of a User entity and several Role Ids can I insert a relationship between the two types of entities without having any other Role data and without doing a select on the Roles first?
如果我是用户和角色之间的多对多关系,并且我有一个用户实体和几个角色ID的实例,我可以在两种类型的实体之间插入关系,而无需任何其他角色数据,也无需对角色第一?
Update:
I might not have been clear enough. I don't have an instance of a Role, only the role id. Is it possible to create the relationship between User and Role without filling a Role object from the database first?
我可能不够清楚。我没有角色的实例,只有角色id。是否可以在不首先从数据库中填充Role对象的情况下创建User和Role之间的关系?
2 个解决方案
#1
Yes if you have the IDs and you need to relate them
是,如果您有ID,则需要将它们关联起来
You should be able to do this (pseudo code)
你应该能够这样做(伪代码)
// how you get this doesn't matter so long as it is in the Context
User user = ...;
Role role = new Role {Id = 2};
// role 2 is in unchanged state
ctx.AttachTo("Roles", role);
// role 2 is unchanged + added relationship between user and role 2
user.Roles.Add(role);
ctx.SaveChanges();
The key here is that AttachTo
puts an entity into the ObjectState manager in the unchanged state. So long as you don't need to modify that entity, and only use if for relationship building, you don't even need to know all the property values, the PK is sufficient.
这里的关键是AttachTo将一个实体放入未更改状态的ObjectState管理器中。只要您不需要修改该实体,并且仅用于建立关系,您甚至不需要知道所有属性值,PK就足够了。
Once you have it attached you can then build the relationship.
一旦你附上它,你就可以建立这种关系。
Hope this helps
希望这可以帮助
Cheers Alex
#2
If you're not using databinding, sure. Many to many gets mapped as list of references to each other. User.Roles.Add(Role ...) should be fine.
如果您没有使用数据绑定,请确保。多对多被映射为彼此的引用列表。 User.Roles.Add(Role ...)应该没问题。
#1
Yes if you have the IDs and you need to relate them
是,如果您有ID,则需要将它们关联起来
You should be able to do this (pseudo code)
你应该能够这样做(伪代码)
// how you get this doesn't matter so long as it is in the Context
User user = ...;
Role role = new Role {Id = 2};
// role 2 is in unchanged state
ctx.AttachTo("Roles", role);
// role 2 is unchanged + added relationship between user and role 2
user.Roles.Add(role);
ctx.SaveChanges();
The key here is that AttachTo
puts an entity into the ObjectState manager in the unchanged state. So long as you don't need to modify that entity, and only use if for relationship building, you don't even need to know all the property values, the PK is sufficient.
这里的关键是AttachTo将一个实体放入未更改状态的ObjectState管理器中。只要您不需要修改该实体,并且仅用于建立关系,您甚至不需要知道所有属性值,PK就足够了。
Once you have it attached you can then build the relationship.
一旦你附上它,你就可以建立这种关系。
Hope this helps
希望这可以帮助
Cheers Alex
#2
If you're not using databinding, sure. Many to many gets mapped as list of references to each other. User.Roles.Add(Role ...) should be fine.
如果您没有使用数据绑定,请确保。多对多被映射为彼此的引用列表。 User.Roles.Add(Role ...)应该没问题。