c# - Delete statement conflicts with Reference constraint -


i assume has simple answer. brand new entity framework , creating test application consisting of contacts , groups objects/entities.

here code delete group:

    private void button_deletegroup_click(object sender, eventargs e)     {         var _selectedgroup = datagridview_groups.selectedrows[0].databounditem group;          try         {             cgcontext.groups.remove(_selectedgroup);             cgcontext.savechanges();              populategroupgrid();             messagebox.show("successfully deleted group database!");         }         catch(exception ex) { messagebox.show("failed delete group database.\r\n\r\n" + ex); }     } 

if delete group contact belongs to, test referential integrity, exception thrown (as should):

"the delete statement conflicted reference constraint "fk_dbo.contacts_dbo.groups_group_id". conflict occurred in database "contactgroups", table "dbo.contacts", column 'group_id'. statement has been terminated."

i catch exception , display message user. if go add new group or contact or anything, transaction fails same exception before:

"the delete statement conflicted reference constraint "fk_dbo.contacts_dbo.groups_group_id". conflict occurred in database "contactgroups", table "dbo.contacts", column 'group_id'. statement has been terminated."

so, i'm not clearing / ending transaction or when initial exception occurs. doing wrong or missing?

use willcascadeondelete(true) withoptional

  modelbuilder.entity<parent>()   .hasmany<child>(c => c.children)   .withoptional(x => x.parent)   .willcascadeondelete(true); 

use include

  var adv = db.adv.include(b => b.features)                   .include(b => b.advdetails)                   .include(b => b.advgallery)                   .firstordefault(b => b.id == id);   db.adv.remove(adv); 

for .hasmany(...).withmany(...) include ok


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -