title: How to get the Count of an Entity Framework Junction Table
body: <p>I have two simple tables, <code>Users</code> and <code>Roles</code>.  Both have their own Primary Key called <code>ID</code> along with a few other unique properties that have nothing to do with this question.  Both tables also have a <code>virtual IList</code> property of the other.  So a <code>User</code> object as the following property:</p>
  
  <pre><code>public virtual IList&lt;Role&gt; Roles { get; set; }
  </code></pre>
  
  <p>And the <code>Role</code> object has the following property:</p>
  
  <pre><code>public virtual IList&lt;User&gt; Users { get; set; }
  </code></pre>
  
  <p>Both allow me to navigate from a <code>User</code> to their <code>Role</code>s or from a <code>Role</code> to its <code>User</code>s with ease in C#.</p>
  
  <p>The <code>EntityTypeConfiguration</code> for the <code>Role</code> has nothing specific to the <code>User</code>.  However, the <code>User</code> has the following for the <code>Role</code> to create the Junction table:</p>
  
  <pre><code>  this.HasMany(x =&gt; x.Roles)
      .WithMany(x =&gt; x.Users)
      .Map(x =&gt; {
        x.ToTable("UserRole", "xref");
        x.MapLeftKey("UserID");
        x.MapRightKey("RoleID");
      });
  </code></pre>
  
  <p>This behaves perfectly for everything I needed to do, up to this point.  Now, I need a way to query the total number of records in that <code>xref.UserRole</code> table.  In SQL I would simply do the following:</p>
  
  <pre><code>SELECT COUNT(*) FROM xref.UserRole
  </code></pre>
  
  <p>and life would be perfect.  But EF takes that Junction table and puts it behind the scenes.  I have no way to do something like:</p>
  
  <pre><code>int TotalJoins = db.UserRoles.Count();
  </code></pre>
  
  <p>I have looked all over here and the web and am not finding anything that is specific to a simple Junction table like this.  Other answers have extra fields or is not a true many-to-many join so it will not work in my case.</p>
  
  <p>Is there a way, with some extension method or deeper property on the DbContext to get to that table so I can use it in a Linq query?  I know I can write a Stored Procedure, but that seems a bit of a kluge.</p>