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

例外がスローされる前に attach を呼び出さずに Remove() を使用しようとすると、リレーションは削除されません。

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

EntityKeysよりも(上記のユーザーのような)スタブエンティティを操作する方がはるかに簡単だと思います。

スタブエンティティの手法の詳細については、このブログ投稿を参照してください。

お役に立てれば

アレックス

于 2009-07-06T02:04:48.010 に答える