2

I have an entity "A" which has ICollection navigation property which contains collection of entities "B".

Let's assume that database contains object "A1" and it's collection property contains 3 entities: "B1, B2, B3".

Now I have in code detached entity "A1" which collection property contains detached entities "B3, B4".

Is it possible to attach object "A1" to the context and mark that Collection property should be updated as well? (entities B1, B2 should be deleted, entity B4 should be added)

I tried the following, but it didn't update the navigation property (Collection) (only scalars properties are updated):

context.Entry(A1).State = EntityState.Modified;
user3653175
  • 101
  • 1
  • 6
  • possible duplicate of [Storing a complex detached object graph in EF6](http://stackoverflow.com/questions/21677558/storing-a-complex-detached-object-graph-in-ef6) – Gert Arnold May 22 '14 at 22:20

2 Answers2

1
            using (var ctx = GetContext())
            {
                int[] ids = ctx.Bs.Select(x => x.Id).ToArray();
                foreach (Bs b in A1.BsCollection)
                {
                    if (!ids.Contains(b.Id))
                        ctx.Bs.Add(b);
                    else if(...){ ... }
                }
                ctx.As.Attach(A1);
                ctx.Entry(A1).State = EntityState.Modified;
                ctx.SaveChanges();
            }
jasdefer
  • 757
  • 12
  • 24
0

you should use Attach which will recursively attach you object

context.As.Attach(A1);

where As is a DbSet exposed by the context.

context.Set<TA>().Attach(A1);

will do also, with TA the type of A1.

tschmit007
  • 7,559
  • 2
  • 35
  • 43
  • I use Attach method. It works fine for attached entity and related entities in relation "one-to-many". In my case, relation between "A" and "B" is "many-to-many" (both entities have collections of each other). It seems that in such case EF just ignore relation "many-to-many". – user3653175 May 23 '14 at 11:18