title: How to get proper DbSet<Entity> in DbContext when SavingChanges?
body: <p>I have a DbContext like</p>
  
  <pre><code>public class MyContext : DbContext
  {
     public DbSet&lt;Entity1&gt; Entities1 { get; set; }
     public DbSet&lt;Entity2&gt; Entities2 { get; set; }
     . . .
  }
  </code></pre>
  
  <p>where <code>Entity1</code> and <code>Entity2</code> inherits base class  </p>
  
  <pre><code>public abstract class BaseEntity
  {
     [DatabaseGenerated(DatabaseGeneratedOption.None)]
     public int Id { get; set; }
     . . .
  }
  </code></pre>
  
  <p>For some reason I needed to remove auto-increment in database and make my custom auto-increment in context in order to avoid database influence. So I decided to estimate current max value in <code>Id</code> column and increment it.<br>
  I created a simple method  </p>
  
  <pre><code>private int GetMaxId(IQueryable&lt;BaseEntity&gt; set)
  {
     if (set.Count() == 0) return 0;
     else return set.Max(x =&gt; x.Id);
  }
  </code></pre>
  
  <p>So in context constructor I do folowing:  </p>
  
  <pre><code>public MyContext() : base("MyConnection")
  {
     . . .
  
     var objectContext = ((IObjectContextAdapter)this).ObjectContext;
     objectContext.SavingChanges += (sender, args) =&gt;
     {
        foreach (var entry in ChangeTracker.Entries())
        {
           var entity = entry.Entity;
           var state = entry.State;
           if (entity is BaseEntity)
           {
              switch (entry.State)
              {
                 case EntityState.Added:
                    var set = Set&lt;entity.GetType()&gt;();
                    (entity as BaseEntity).Id = GetMaxId(set) + 1;
                 . . .
              }
           }
        }
        ChangeTracker.DetectChanges();
     };
  
     . . .
  }
  </code></pre>
  
  <p>But the thing is I can't construct DbSet like <code>Set&lt;entity.GetType()&gt;()</code> as well as <code>Set&lt;typeof(entity)&gt;()</code> - it says that last <code>)</code> is invalid expression. Although It doesn't depend on amount\order of brackets.<br>
  <code>Set(entity.GetType())</code> doesn't suit for me too because it returns an untyped DbSet.  </p>
  
  <p>Please, tell me how to resolve this problem or what I'm doing wrong.</p>