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

希望這有助於

亞歷