How to add/remove many-to-many relation with entity framework by entity key?

跟風遠走 提交于 2019-12-12 20:54:38

问题


I tried:

using (Entities e = new Entities())
{
    EntityKey key = new EntityKey("Entities.Users", "UserId", 20);
    User user = new User { EntityKey = key};
    Role role = e.Roles.FirstOrDefault();
    //role.Users.Attach(user); //throws (when uncommented...) InvalidOperationException:
    //The object being attached to the source object is not attached to the same ObjectContext as the source object.
    role.Users.Add(user); //throws InvalidOperationException too:
    //The object cannot be added to the ObjectStateManager because it already has an EntityKey. Use ObjectContext.Attach to attach an object that has an existing key.
    e.SaveChanges();
}

When trying to use Remove() without calling attach before no exception is thrown but relation not deleted.


回答1:


Try something like this:

User user = new User {UserId = 20};
e.AttachTo("Users", user);
Role role = e.Roles.FirstOrDefault();
role.Users.Add(user);
e.SaveChanges();

I find it much easier to work with Stub Entities (like the above user) rather than EntityKeys.

See this blog post for more info on Stub Entity techniques.

Hope this helps

Alex



来源:https://stackoverflow.com/questions/1077554/how-to-add-remove-many-to-many-relation-with-entity-framework-by-entity-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!