2

我想:如何通过实体键添加/删除与实体框架的多对多关系?

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

当尝试使用删除(),而不调用连接抛出之前也不例外,但不会删除关系。

+0

是在你的类型System.Data.Entity.DbContext的例子 “实体”? – jaybro 2017-05-09 21:19:53

回答

3

尝试这样:

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

我觉得它更容易与存根实体的工作(如上述用户),而不是EntityKeys。

有关存根实体技术的更多信息,请参见此blog post

希望这有助于

亚历