c# - Entity Framework error, only when deleting "multiple" Parent then Child row -
i'm building , mvc project using entity-framework 6 (code first).
my database data models (code first):
public class parentnode { public int parentnodeid { get; set; } public string someparentdata { get; set; } //fk [required] public int childnodeid { get; set; } public virtual childnode childnode { get; set; } } public class childnode { public int childnodeid { get; set; } public string somechildishdata { get; set; } //references table/model public virtual icollection<parentnode> parentnodes{ get; set; } }
the issue: deleting multiple childnodes
- i won't rely on cascade delete
- parentnode->childnode has many 1 relation. in case need delete 1 childnode, first delete parentnode childnode ()
- deleting 1 childnode done this:
deleting 1 childnode: no problem (if 1 present in list)
deleting multiple childnodes: fk null reference error occurs
{ ... foreach(parentnode parenttodelete in parentnodelist) { db.entry(parenttodelete).state = entitystate.deleted; db.savechanges(); } foreach(childnode childtodelete in childnodelist) { db.entry(childtodelete).state = entitystate.deleted; db.savechanges(); //error exception occurs here!! } ... }
error message:
an exception of type 'system.invalidoperationexception' occurred in entityframework.dll not handled in user code
additional information: operation failed: relationship not changed because 1 or more of foreign-key properties non-nullable. when change made relationship, related foreign-key property set null value. if foreign-key not support null values, new relationship must defined, foreign-key property must assigned non-null value, or unrelated object must deleted.
table rows state when error occurred
parent
pk: restaurantmenucategoryid
fk: restaurantmenunameid
child
pk: restaurantmenunameid
as can see parent table still has reference child row restaurantmenunameid == 2, whilst expected behaviour parent reference should have been deleted before accessing child table.
my observations:
- by looking @ database, seems when db.savechanges() occurs parent node, though delete query in database hasn't occurred, code keeps on moving asynchronously. synchronous behaviour should used, instead of fire , forget?
- an other possibility dbcontext isn't updated after parent delete, have been true if looking @ db parent rows deleted "still there". going on?
question: please let me know problem is, main topics related issue?
Comments
Post a Comment