c# - Updating detached entities in Entity Framework -


loading parents db, closing context. after point when parents processed(added toys children, toys can shared amongst children: many many relationship), need updated , each 1 updated once.

public class parent {     public int parentid { get; set; }     public virtual list<child> children { get; set; } }  public class child {     public int childid { get; set; }      public int parentid { get; set; }     public virtual parent parent { get; set; }      public virtual list<toy> toys { get; set; } }  public class toy {     public int toyid { get; set; }      public virtual list<child> child { get; set; } } 

they have other properties, toys of each children inserted. parents updated in db.

public void updateparents(list<parent> parents) {     using (var ctx = new context())     {         foreach (var parent in parents)         {             parent.children.foreach(c => c.toys.foreach(                 t => ctx.entry(t).state = entitystate.added));              ctx.parents.attach(parent);             ctx.entry(parent).state = entitystate.modified;         }          ctx.savechanges();     } } 

updating method works, slower process should be. when tried execute method more times behaved differently first run. each following run not insert new toys, instead duplicates children of parents.

is there better , correct(update more times possible) way need?

edit: changing state of children modified fixed duplicates problem

ctx.entry(c).state = entitystate.modified; 


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -