c# - Delete using navigation properties in EF 6 -


i using ef 6 database modal in application. have table tbl_user has 1:n relationship in other table. 1 of them tbl_user_case primary key of tbl_user act foreign key in tbl_user_case.

now deleting user tbl_user. before need delete corresponding entries in tbl_user_case. using following code that

 private long deleteuser(long userid)     {         using(verbatrackentities datacontext = new verbatrackentities())         {             tbl_user user = datacontext.tbl_user.where(x => x.lng_user_id == userid).singleordefault();             if(user != null)             {                 foreach (var cases in user.tbl_user_case.tolist())                 {                     user.tbl_user_case.remove(cases);                                           }             }             datacontext.savechanges();         }         return 0;     } 

here m getting exception

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

how can operation correctly ??

ok, if goal delete user, can let framework handle child-relations. can try this:

private long deleteuser(long userid) {     using(verbatrackentities datacontext = new verbatrackentities())     {         tbl_user user = datacontext.tbl_user.                                  singleordefault(x => x.lng_user_id == userid);         if(user != null)         {                    datacontext.tbl_user.remove(user);              datacontext.savechanges();         }     }     return 0; } 

update: can try one:

private long deleteuser(long userid) {     using(verbatrackentities datacontext = new verbatrackentities())     {         tbl_user user = datacontext.tbl_user                              .singleordefault(x => x.lng_user_id == userid);         if(user != null)         {             foreach (var cases in user.tbl_user_case.tolist())             {                 //little modification here                 datacontext.tbl_user_case.remove(cases);                                       }         }         datacontext.savechanges();     }     return 0; } 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -