c# - Remove entity with related entities in EntityFramework -
i have following code:
[httppost] public actionresult eliminar(usuario usuario) { db.usuarios.attach(usuario); usuario.transacciones.tolist().foreach(t => db.transacciones.remove(t)); usuario.eventos.tolist().foreach(e => db.eventos.remove(e)); db.usuarios.remove(usuario); db.savechanges(); return redirecttoaction("index"); } i can't make work. know delete entity first have attach it, isn't working entity has relations. i've tried foreach loop, , attaching each transaccion , evento entities before removing them, doesn't work neither.
this error innerexception contains:
system.data.sqlclient.sqlexception: delete statement conflicted reference constraint "fk_tr_us". conflict occurred in database "bd_dm", table "dbo.transacciones", column 'idusuario'. statement has been terminated.
i know means, don't know how make code work. need remove first transacciones , eventos related usuario, able remove usuario.
after lot of debugging (in remote server) found out problem was. usuario usuario data passed eliminar method correctly, related objects not. have load them before being able remove them, , remove usuario object.
this final code:
[httppost] public actionresult eliminar(usuario usuario) { db.usuarios.attach(usuario); db.entry(usuario).collection("transacciones").load(); db.entry(usuario).collection("eventos").load(); usuario.transacciones.tolist().foreach(t => db.transacciones.remove(t)); usuario.eventos.tolist().foreach(e => db.eventos.remove(e)); db.usuarios.remove(usuario); db.savechanges(); return redirecttoaction("index"); }
Comments
Post a Comment