Entity Framework updating detached objects

07/25/2017 18:54 Buckyx#1
Guys I need your help

Loading parents from DB, then closing context. After certain point when those parents are processed(added toys to their children, toys can be shared amongst children: many to many relationship), they need to be updated and each one is updated only once.

Code:
    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, but only toys of each children are inserted. then parents are updated in DB.

Code:
    public void UpdateParents(List<Parent> parents)
    {
        using (var ctx = new Context())
        {
            foreach (var parent in parents)
            {
                parent.Children.ForEach(c => 
                {
                    ctx.Entry(c).State = EntityState.Modified;
                    c.Toys.ForEach(t => ctx.Entry(t).State = EntityState.Added));
                }

                ctx.Parents.Attach(parent);
                ctx.Entry(parent).State = EntityState.Modified;
            }

            ctx.SaveChanges();
        }
    }
Is there a better way to update detached entities which contains many to many relationship?

edit..fixed the initial problem, however I still need to optimize
edit2.. graphdiff solved the initial problem in a better fashion, still not optimal but I guess thats too much work for bulk update which also update relates entities to be worth