title: How to query the DbSets of all types that implement an interface?
body: <p>Many of my data models use this interface: </p>
  
  <pre><code>public interface IHasPrimaryImageProperty
  {
      PrimaryImageDataModel PrimaryImage { get; set; }
      int? PrimaryImageId { get; set; }
  }
  </code></pre>
  
  <p>Where <code>PrimaryImageDataModel</code> is: </p>
  
  <pre><code>public class PrimaryImageDataModel
  {
      public int Id { get; set; }
      public string ImageFile { get; set; }
      public int TotalItemsUsingImage { get; set; }
  }
  </code></pre>
  
  <p>I want populate <code>PrimaryImageDataModel.TotalItemsUsingImage</code>, by performing counts on all data models that implement <code>IHasPrimaryImageProperty</code>. </p>
  
  <p>So far I have managed to get a list of types that implement the <code>IHasPrimaryImageProperty</code>. </p>
  
  <p>But I haven't been able to get the total for each Type. </p>
  
  <p>Please see the example below for a demonstration of what I would like to acheive. </p>
  
  <pre><code>public static PrimaryImageDataModel GetImageUsageTotals(PrimaryImageDataModel image)
  {
      var typesUsingImage = GetTypesWithPrimaryImageProperty();
      int totalUsingImage = 0;
      foreach (Type typeUsingImage in typesUsingImage)
      {
          // I WOULD LIKE TO DO SOMETHING LIKE THIS
          totalForType = db.Set&lt;typeUsingImage&gt;()
              .Where(x =&gt; x.PrimaryImageId == image.Id)
              .Count()
  
          totalUsingImage += totalForType;
      }
      image.TotalItemsUsingImage = totalUsingImage;
      return image;
  }
  
  
  public static IEnumerable&lt;Type&gt; GetTypesWithPrimaryImageProperty()
  {
      var currentAssembly = Assembly.GetExecutingAssembly();
      foreach (Type type in currentAssembly.GetTypes())
      {
          if (type.GetInterfaces().Contains(typeof(IHasPrimaryImageProperty)))
          {
              yield return type;
          }
      }
  }
  </code></pre>