Question

J'ai essayé:

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

Lorsque vous essayez d'utiliser remove () sans appeler avant d'attacher aucune exception est levée, mais par rapport pas supprimé.

Était-ce utile?

La solution

Essayez quelque chose comme ceci:

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

Je trouve beaucoup plus facile de travailler avec les entités Stub (comme l'utilisateur ci-dessus) plutôt que EntityKeys.

Voir cette blog pour plus d'informations sur les techniques Stub entité.

Hope this helps

Alex

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top