Pregunta

He intentado:

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

Al intentar utilizar Eliminar () sin llamar antes de adjuntar ninguna excepción se produce pero no se elimina relación.

¿Fue útil?

Solución

Trate algo como esto:

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

Me resulta mucho más fácil trabajar con Entidades de rutas internas (como el usuario anterior) en lugar de EntityKeys.

Vea este entrada de blog para obtener más información sobre las técnicas del trozo de entidad.

Espero que esto ayude

Alex

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top