asp.net - In Entity Framework, how to delete record with foreign key constraint? -


this question has answer here:

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

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -