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
Post a Comment