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();
}
を削除する(使用しようとする場合)例外がスローされないが、関係は削除されません前に、添付呼び出さず。私はそれがはるかに簡単スタブ(上記のユーザーのような)エンティティではなく、EntityKeysで動作するように見つける
User user = new User {UserId = 20};
e.AttachTo("Users", user);
Role role = e.Roles.FirstOrDefault();
role.Users.Add(user);
e.SaveChanges();
:
を助け
ホープタイプSystem.Data.Entity.DbContextのあなたの例では、 "エンティティ" となっていますか? – jaybro
調査後:「AttachTo」が使用されている場合、「Entities」はObjectContextでなければなりません。 – jaybro
おそらく、それは古い投稿です...追加されたタグ – Shimmy