asp.net - In Entity Framework, how to delete record with foreign key constraint? -
this question has answer here:
- entity framework cascade delete 2 answers
i have method delete "project" record in database, , "option items" associated it.
public bool deleteprojectbyid(int id) { using (dbcontext db = new dbcontext(confighelper.instance().connectionstring)) { try { foreach (var entity in db.projectoptionitems.where(o => o.projectid == id)) db.projectoptionitems.deleteobject(entity); db.savechanges(); var project = db.projects.singleordefault(o => o.id == id); db.projects.deleteobject(project); db.savechanges(); return true; } catch (exception e) { errorloggingservice.log(this, e); return false; } } }
this works fine. if comment out first call db.savechanges, way how hoping code be, result sql exception (the delete statement conflicted reference constraint).
having 2 calls savechanges() works surely not way it. please help. thanks!
like aliriza said, set in sql server. additionally use in dbcontext
class:
protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<projectoptionitems>().willcascadeondelete(); }
Comments
Post a Comment