title: Select top1 with Linq
body: <p>Actually I’m working with Linq and UOW (unit of work), and I'm doing all of the easy access to bbdd with linq. I know that if I want to get the first row of one table, I can do this:</p>
  
  <pre><code>int test4 = (from p 
               in uow.ProductR.context.product 
               where p.Id == 1715 select p.Id).FirstOrDefault();
  </code></pre>
  
  <p>That will execute this in SQL Server:</p>
  
  <pre><code>SELECT TOP (1) 
      [Extent1].[Id] AS [Id]
      FROM [dbo].[product] AS [Extent1]
      WHERE 1715 = [Extent1].[Id]
  </code></pre>
  
  <p>My questions is, can I do the same with LINQ to object with the generic repositories of my UOW? I mean, when I execute</p>
  
  <pre><code>int test2 = uow.ProductR.Get(p =&gt; p.Id == 1715).Select(p =&gt; p.Id).FirstOrDefault();
  </code></pre>
  
  <p>Or</p>
  
  <pre><code>var test3 = uow.ProductR.Get(p =&gt; p.Id == 1715).Select(p =&gt; new { p.Id });
  </code></pre>
  
  <p>In SQL Server I get:</p>
  
  <pre><code>SELECT 
  [Extent1].[Id] AS [Id], 
  [Extent1].[Name] AS [Name], 
  FROM [dbo].[product] AS [Extent1]
  WHERE 1715 = [Extent1].[Id]
  </code></pre>
  
  <p>Of course, with the second way, when the database has 500k rows, it will be slow. (I have more columns, not only 2)</p>
  
  <p>Edited: Here is the Class with the GET declarations</p>
  
  <pre><code>public class GenericRepository&lt;TEntity&gt; : IGenericRepository&lt;TEntity&gt; where TEntity : class
  {
  
      internal contextEntities context;
      internal DbSet&lt;TEntity&gt; dbSet;
  
      public GenericRepository(contextEntities context)
      {
          this.context = context;
          this.dbSet = context.Set&lt;TEntity&gt;();
      }
  
      public virtual IEnumerable&lt;TEntity&gt; Get(
          Expression&lt;Func&lt;TEntity, bool&gt;&gt; filter = null,
          Func&lt;IQueryable&lt;TEntity&gt;, IOrderedQueryable&lt;TEntity&gt;&gt; orderBy = null,
          string includeProperties = "")
      {
          IQueryable&lt;TEntity&gt; query = this.dbSet;
  
          if (filter != null)
          {
              query = query.Where(filter);
          }
  
          foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
          {
              query = query.Include(includeProperty);
          }
  
          if (orderBy != null)
          {
              return orderBy(query).AsQueryable();
          }
          else
          {
              return query.AsQueryable();
          }
      }
  }
  </code></pre>
  
  <p>I hope I have explained well.</p>