title: Update parent and child collections on generic repository with EF Core
body: <p>Say I have a <code>Sale</code> class:</p>
  
  <pre><code>public class Sale : BaseEntity //BaseEntity only has an Id  
  {        
      public ICollection&lt;Item&gt; Items { get; set; }
  }
  </code></pre>
  
  <p>And an <code>Item</code> class:</p>
  
  <pre><code>public class Item : BaseEntity //BaseEntity only has an Id  
  {
      public int SaleId { get; set; }
      public Sale Sale { get; set; }
  }
  </code></pre>
  
  <p>And a Generic Repository (update method):</p>
  
  <pre><code>    public async Task&lt;int&gt; UpdateAsync&lt;T&gt;(T entity, params Expression&lt;Func&lt;T, object&gt;&gt;[] navigations) where T : BaseEntity
      {
          var dbEntity = _dbContext.Set&lt;T&gt;().Find(entity.Id);
  
          var dbEntry = _dbContext.Entry(dbEntity);
  
          dbEntry.CurrentValues.SetValues(entity);            
  
          foreach (var property in navigations)
          {
              var propertyName = property.GetPropertyAccess().Name;
  
              await dbEntry.Collection(propertyName).LoadAsync();
  
              List&lt;BaseEntity&gt; dbChilds = dbEntry.Collection(propertyName).CurrentValue.Cast&lt;BaseEntity&gt;().ToList();
  
              foreach (BaseEntity child in dbChilds)
              {
                  if (child.Id == 0)
                  {
                      _dbContext.Entry(child).State = EntityState.Added;
                  }
                  else
                  {
                      _dbContext.Entry(child).State = EntityState.Modified;
                  }
              }
          }
  
          return await _dbContext.SaveChangesAsync();
      }
  </code></pre>
  
  <p>I'm having difficulties to update the <code>Item</code> collection on the <code>Sale</code> class. With this code I managed to <code>add</code> or <code>modify</code> an <code>Item</code>. But, when I <code>delete</code> some item on the <code>UI</code> layer, nothing gets deleted.</p>
  
  <p>Does <code>EF Core</code> have something to deal with this situation, while using a generic repository patter?</p>
  
  <p>UPDATE</p>
  
  <p>Seems to be that <code>Items</code> tracking is lost. Here is my generic retrieve method with includes.</p>
  
  <pre><code>    public async Task&lt;T&gt; GetByIdAsync&lt;T&gt;(int id, params Expression&lt;Func&lt;T, object&gt;&gt;[] includes) where T : BaseEntity
      {
          var query = _dbContext.Set&lt;T&gt;().AsQueryable();
  
          if (includes != null)
          {
              query = includes.Aggregate(query,
                (current, include) =&gt; current.Include(include));
          }
  
          return await query.SingleOrDefaultAsync(e =&gt; e.Id == id);
      }
  </code></pre>