zzzprojects / GraphDiff

GraphDiff is a library that allows the automatic update of a detached graph using Entity Framework code first.
https://entityframework-graphdiff.net/overview
MIT License
333 stars 101 forks source link

Update and delete children collection at once #150

Open aureole82 opened 9 years ago

aureole82 commented 9 years ago

Hi

I got this "simple" model

    public class Container
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public List<Item> Items { get; set; } = new List<Item>();
    }
    public class Item
    {
        public int Id { get; set; }
        public string Name { get; set; }

        public List<Item> LinkedItems { get; set; } = new List<Item>();
    }

In order to get the Item n-m Item relation inside an extra table I put the following inside OnModelCreating method

    modelBuilder.Entity<Item>()
        .HasMany(item => item.LinkedItems)
        .WithMany()
        .Map(configuration =>
        {
            configuration
                .MapLeftKey("From_ItemId")
                .MapRightKey("To_ItemId")
                .ToTable("ItemLinks");
        });

So let's assume

  1. That's inside the DB:
    • Container#1 { Items={ Item#1, Item#2, Item#3 } }
    • Container#2 { Items={ Item#4{ LinkedItems={ Item#1, Item#2 } } }
  2. I create a new Container
  3. Move existing Item#4 inside it.
  4. Modify its linked items (1xUpdate Item#1, 1xDelete reference Item#2)
    var newContainer = new Container { 
        Name = "new",
        Items = {
            new Item {Id = 4, Name = "#4", LinkedItems = {new Item {Id = 1, Name = "#1"} }}
        }
    };

My question is: *Is their a single UpdateGraph() call to

  1. remove Item#4 from Container#2 AND
  2. delete not mentioned reference Item#4 -> Item#2

I finally got it running but I need 2 calls:

    _context.UpdateGraph(newContainer,
        map => map.AssociatedCollection(c => c.Items)
        );
    _context.UpdateGraph(item4,
        map => map.AssociatedCollection(i => i.LinkedItems)
        );
    _context.SaveChanges();

But this solution doesn't help very much since I have to run the second UpdateGraph on each child!