title: How to generalise access to DbSet<TEntity> members of a DbContext?
body: <p>I have a <code>DbContext</code> with several of the following type of members:</p>
  
  <pre><code>public DbSet&lt;JobLevel&gt; JobLevels { get; set; }
  public DbSet&lt;Country&gt; Countries { get; set; }
  public DbSet&lt;Race&gt; Races { get; set; }
  public DbSet&lt;Language&gt; Languages { get; set; }
  public DbSet&lt;Title&gt; Titles { get; set; }
  </code></pre>
  
  <p>All these are <code>where T: IdNamePairBase</code>, which has <code>Id</code> and <code>Name</code> members only. I am trying desperately to find a common interface with which to access any of these members, to generalise the following MVC3 controller code into one controller:</p>
  
  <pre><code>public ActionResult Edit(DropDownListModel model, Guid)
  {
      var dbSet =  _dbContext.Countries;
      var newItems = model.Items.Where(i =&gt; i.IsNew &amp;&amp; !i.IsDeleted).Select(i =&gt; new { i.Name });
      foreach (var item in newItems)
      {
          if (!string.IsNullOrWhiteSpace(item.Name))
          {
              var undead = ((IEnumerable&lt;IdNamePairBase&gt;)dbSet).FirstOrDefault(p =&gt; p.Name.ToLower() == item.Name.ToLower());
              if (undead != null)
              {
                  // Assign new value to update to the new char. case if present.
                  undead.Name = item.Name;
                  undead.IsDeleted = false;
                  _dbContext.SaveChanges();
                  continue;
              }
              var newPair = new Country { Name = item.Name };
              dbSet.Add(newPair);
              _dbContext.SaveChanges();
          }
      }
      return RedirectToAction("Edit", new {listName = model.ListName});
  }
  </code></pre>
  
  <p>How could I go about resolving my problem that right now I need one controller for each of the <code>DbContext</code> members, like the one above is dedicated to <code>DbSet&lt;Country&gt; Countries</code>?</p>
  
  <p><strong>PARTIAL SOLUTION:</strong> Along lines similar to GertArnold's answer below, before I knew about the <code>_dbContext.Set&lt;T&gt;</code> all he highlights, I implemented this method on my context class to get sets of a specific type:</p>
  
  <pre><code>public IEnumerable&lt;DbSet&lt;T&gt;&gt; GetDbSetsByType&lt;T&gt;() where T : class
  {
      //var flags = BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance;
      var props = GetType().GetProperties()
          .Where(p =&gt; p.PropertyType.IsGenericType &amp;&amp; p.PropertyType.Name.StartsWith("DbSet"))
          .Where(p =&gt; p.PropertyType.GetGenericArguments().All(t =&gt; t == typeof(T)));
      return props.Select(p =&gt; (DbSet&lt;T&gt;)p.GetValue(this, null));
  }
  </code></pre>