c# - Removing child entity not deleting in database entity framework -


i have 2 entities "yogaspace" , "yogaspaceimage" i'm deleting image , trying row removed, instead nulls out reference yogaspace entity.

here entities.

public class yogaspace {     public int yogaspaceid { get; set; }     public virtual icollection<yogaspaceimage> images { get; set; } }  public class yogaspaceimage {     public int yogaspaceimageid { get; set; }     public byte[] image { get; set; }     public byte[] imagethumbnail { get; set; }     public string contenttype { get; set; }     public int ordering { get; set; } } 

here method deleted 1 image db.

[httppost]     public actionresult removeimage(string id, string imageid)     {         yogaspace yogaspace = yogaspacerepository.find(convert.toint16(id));         yogaspaceimage image = yogaspace.images.firstordefault(si => si.yogaspaceimageid == convert.toint16(imageid));         yogaspace.images.remove(image);          yogaspacerepository.insertorupdate(yogaspace);         yogaspacerepository.save();          return json("removed");     } 

here what's inside repo insertorupdate()

public void insertorupdate(yogaspace yogaspace)     {         if (yogaspace.yogaspaceid == default(int))         {             context.entry(yogaspace).state = system.data.entity.entitystate.added;         }         else         {             context.entry(yogaspace).state = system.data.entity.entitystate.modified;         }     } 

and here result. can see row doesn't deleted, null gets put reference column. don't have repo yogaspaceimage entity, yogaspace trying use don't have create repo. enter image description here

you need mark entity deleted.

yogaspace.images.remove(image); context.yogaspaceimages.remove(image) 

your other option mark mapping .willcascadeondelete()

e.g.

protected override void onmodelcreating(dbmodelbuilder mb) {      mb.entity<yogaspace>().hasmany(p => p.images )         .withrequired()         .hasforeignkey(c => c.yogaspaceimageid)         .willcascadeondelete();  }  

the other option have foreignkey on yogaspaceimage yogaspace (if mapping of 1 yogaspace - 0-many image) , mark yogaspaceimage.yogaspace foreign key required. therefore whenever ef tried remove foreign key, automatically delete image.

public class yogaspaceimage {     public int yogaspaceimageid { get; set; }             public byte[] image { get; set; }     public byte[] imagethumbnail { get; set; }     public string contenttype { get; set; }     public int ordering { get; set; }      public int yogaspaceid { get; set; }     [required] <-- delete image, if removed parent     public virtual yogaspace yogaspace { get; set; } } 

Comments

Popular posts from this blog

c++ - Delete matches in OpenCV (Keypoints and descriptors) -

java - Could not locate OpenAL library -

sorting - opencl Bitonic sort with 64 bits keys -