c# - Deleting principal and dependents for independent association (one-to-many) -


using entity framework 6 designer, our entities have independent association. no foreign keys defined in our model's properties.

having following entities one-to-many relationship:

public class parent {     public guid id { get; set; }     public virtual icollection<child> children { get; set; } } public class child {     public guid id { get; set; }     public virtual parent parent { get; set; } } 

mapping following sql tables:

create table parent (     id uniqueidentifier not null,     constraint pk_parent primary key clustered (id) )  create table child (     id uniqueidentifier not null,     fkparent uniqueidentifier not null,     constraint pk_child primary key clustered (id) )  alter table child check add constraint fk_child_parent foreign key(fkparent) references parent ([id])  alter table child check constraint fk_child_parent 

as can see not using cascade on delete, because team against usage of it.

so question is, what's correct way delete parent , it's dependent children given parent's id?
delete, mean sql records in both tables should deleted (resulting in delete sql statement) after calling .savechanges().

so way figured out how achieve this, explicitly loading children memory , deleting them 1 one before deleting parent.

using (var context = new mydbcontext()) {     var parent = context.parents.find(parentid);     //or use linq if prefer:     var alternative = context.parents.single(p => p.id == parentid)      foreach(var child in parent.children.tolist())     {         context.children.remove(child);     }      context.parents.remove(parent);      context.savechanges(); } 

note .tolist() (or .toarray() if prefer) on children important, explained in this answer.

performance-wise not ideal, because have query every child record database , load memory (i suppose small application, wouldn't matter though). couldn't find better approach without using cascade on delete, though i'm not sure if outperform case.


Comments

Popular posts from this blog

serialization - Convert Any type in scala to Array[Byte] and back -

matplotlib support failed in PyCharm on OSX -

python - Matplotlib: TypeError: 'AxesSubplot' object is not callable -