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

当尝试使用 Remove() 而不调用 attach 之前没有抛出异常但没有删除关系。

4

1 回答 1

3

尝试这样的事情:

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

我发现使用 Stub Entities(如上面的用户)而不是 EntityKeys 更容易。

有关 Stub Entity 技术的更多信息,请参阅此博客文章

希望这可以帮助

亚历克斯

于 2009-07-06T02:04:48.010 回答