如何添加或删除多对多关系,与实体的框架,通过实体的钥匙吗?
-
21-08-2019 - |
题
我试过:
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();
}
当试图使用Remove()而不调用附加前没有异常,但有关不删除。
解决方案
试试这样的事情:
User user = new User {UserId = 20};
e.AttachTo("Users", user);
Role role = e.Roles.FirstOrDefault();
role.Users.Add(user);
e.SaveChanges();
我发现它很容易的工作与短的实体(如上述用户),而不是EntityKeys.
看看这个 博客 更多信息Stub实体的技术。
希望这可以帮助
亚历克斯
不隶属于 StackOverflow