2
votes

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;
2

2 Answers

1
votes
            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();
            }
0
votes

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.