Como adicionar / remover muitos-para-muitos relação com a estrutura de entidade por chave de entidade?
-
21-08-2019 - |
Pergunta
Eu tentei:
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();
}
Ao tentar usar Remove () sem chamar anexar antes nenhuma exceção é acionada, mas relação não excluída.
Solução
Tente algo parecido com isto:
User user = new User {UserId = 20};
e.AttachTo("Users", user);
Role role = e.Roles.FirstOrDefault();
role.Users.Add(user);
e.SaveChanges();
Acho que é muito mais fácil trabalhar com as entidades Stub (como o usuário acima) em vez de EntityKeys.
Veja este Blog Post para mais informações sobre técnicas de Stub de entidade.
Espero que isso ajude
Alex
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow