[英]Remove entity with related entities in EntityFramework
我有以下代碼:
[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");
}
我不能讓它發揮作用。 我知道刪除一個實體首先必須附加它,但它不適用於有關系的實體。 我也試着做foreach
循環,並連接各Transaccion
和Evento
刪除它們之前的實體,但它不工作也沒有。
這是InnerException
包含的錯誤:
System.Data.SqlClient.SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_TR_US". The conflict occurred in database "bd_dm", table "dbo.Transacciones", column 'idUsuario'. The statement has been terminated.
我知道這意味着什么,但我不知道如何使代碼工作。 我需要刪除首先是Transacciones
和Eventos
相關Usuario
,能夠去除Usuario
。
經過大量調試(在遠程服務器中)后,我發現了問題所在。 Usuario usuario數據正確傳遞給Eliminar方法,但相關對象不是。 所以我必須加載它們才能刪除它們,然后刪除Usuario對象。
這是我的最終代碼:
[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");
}
這可能對你沒有幫助,但可以幫助那些看到這個的人(就像我在研究這個問題時所做的那樣)。
如果在數據庫上設置了“cascade on delete”,則無需執行上述正在進行的foreach / remove組合。 有幾種方法可以做到這一點,但“編程實體框架:代碼優先”中的這一章https://www.safaribooksonline.com/library/view/programming-entity-framework/9781449317867/ch04s04.html解釋得非常好。
在你的情況下:
usuario.Transacciones
usuario.Eventos
只需進入該關聯的類,並在反向鍵(可能在這種情況下,公共虛擬Usuarios;,在關聯類中)添加裝飾器[必需],這將更改外鍵,使其在刪除時級聯。
如果不這樣做,那些關聯將被設置為null而不是被刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.