c# - Deleting Optional 1-to-Many Does Not Set Foreign Key to Null -


i have 2 entities have optional 1-to-many relationship defined , configured such:

public class  {    // ...    public int? bid { get; set; }    public b b { get; set; } }  public class b  {    // ...    public virtual icollection<a> { get; set; } }   public class aconfiguration : entitytypeconfiguration<a> {      public a()       {          // ...          hasoptional(r => r.b).withmany(r => r.as).hasforeignkey(r => r.bid);      } } 

when deleting on entity of type b expect entities of type have foreign key b entity being deleted have bid foreign key set null. delete operation defined thusly:

public void deleteb(int bid) {     var entity = _context.bs.single(b => b.id == bid);     _context.bs.remove(entity);     _context.savechanges(); } 

however not happen. entity of type b deleted, bid on entities still non-null , other calls .savechanges() throw exceptions because bids referencing rows no longer exist.

how can delete b entities in manner nullify bid properties without having manually iterate on collection during delete operation?

the foreign keys automatically set null if associated entities have been loaded context. in other words, when b removed, associated set of type a have bid property set null if entities of type a had been loaded context. otherwise, ef not have knowledge of existence (unless ef provider automatically generates sql set foreign keys null...which doesn't in sql server case).

one option (if don't mind loading entities):

public void deleteb(int bid) {     var entity = _context.bs.single(b => b.id == bid);     _context.entry(entity).collection(b => b.as).load();      _context.bs.remove(entity);     _context.savechanges(); } 

another option write own sql statement , run that.


Comments