title: Entity Framework : better way to do many to many query?
body: <p>Environment: EF6 code first</p>
  
  <p>I have two tables e.g <code>user</code> and <code>activity</code> which have a many-to-many relation.</p>
  
  <p>I want to know whether any user's activity has a given key, using Entity Framework in an asp.net mvc application.</p>
  
  <ol>
  <li><p>is the following query performance wise?</p></li>
  <li><p>is there any other way to write this query?</p></li>
  </ol>
  
  <p>Query:</p>
  
  <pre><code>var userEntity = _dbcontext.Users.Find(userId);
  
  var isAvailable = _dbcontext.Entry(userEntity)
                              .Collection(e =&gt; e.Activities)
                              .Query().Any(e =&gt; e.Name== "givenname");
  </code></pre>
  
  <p><strong>updated:</strong></p>
  
  <p>i ran those queries and here are the time to run:</p>
  
  <p><strong>1</strong></p>
  
  <pre><code>var userEntity = _dbcontext.Users.Find(userId);
  
  var isAvailable = userEntity.Activities.Any(a =&gt; a.Name == "givenname");
  </code></pre>
  
  <p><strong>time:    5.39s</strong> + time to fetch user</p>
  
  <p><strong>2</strong></p>
  
  <pre><code>var isAvailable =_dbcontext.Users.Include(e =&gt; e.Activities)
                               .Any( u =&gt; u.UserId == userId 
                                      &amp;&amp;  u.Activities.Any(a =&gt; a.Name == "givenname")
                                   );
  </code></pre>
  
  <p><strong>time:     5.73s</strong> </p>
  
  <p><strong>3</strong></p>
  
  <pre><code>var userEntity = _dbcontext.Users.Find(userId);
  
  var isAvailable = _dbcontext.Entry(userEntity)
                          .Collection(e =&gt; e.Activities)
                          .Query().Any(e =&gt; e.Name== "givenname");
  </code></pre>
  
  <p><strong>time:     5.95s</strong>  + time to fetch user</p>
  
  <p>so it seems that choosing the second form of query be reasonable.</p>