title: Entity Framework database query very slow
body: <p>In my database there are <code>Document</code> and <code>DocumentFile</code> tables. Primary key - column <code>Uid</code> (in both tables). <code>DocumentFile</code> references <code>Document</code> via column <code>DocumentUid</code>.</p>
  
  <p>I know uid of document file, and I want to select document with files (with left join), and EF generates this query:</p>
  
  <pre><code>DECLARE @p__linq__0 uniqueidentifier,@p__linq__1 uniqueidentifier,@p__linq__2 varchar(max) ,@p__linq__3 nvarchar(max) ,@p__linq__4 uniqueidentifier
  
  SELECT @p__linq__0=NULL,@p__linq__1=NULL,@p__linq__2=NULL,@p__linq__3=NULL,@p__linq__4='8670AD28-9FA6-41F3-94B9-6B91FD2AE110'
  
  SELECT 
  *
  FROM  [dbo].[Document] AS [Extent1]
  LEFT OUTER JOIN [dbo].[DocumentFile] AS [Extent2] ON [Extent1].[Uid] = [Extent2].[DocumentUid]
  WHERE ((([Extent1].[EntityUid] = @p__linq__0) AND (@p__linq__0 IS NOT NULL)) OR (@p__linq__1 IS NULL)) 
          AND ((([Extent1].[EntityTypeCode] = @p__linq__2) AND ( NOT ([Extent1].[EntityTypeCode] IS NULL OR @p__linq__2 IS NULL))) OR (([Extent1].[EntityTypeCode] IS NULL) AND (@p__linq__2 IS NULL)) OR (@p__linq__3 IS NULL) OR (( CAST(LEN(@p__linq__3) AS int)) = 0)) 
          AND ((([Extent2].[Uid] = @p__linq__4) AND ( NOT ([Extent2].[Uid] IS NULL OR @p__linq__4 IS NULL))) OR (([Extent2].[Uid] IS NULL) AND (@p__linq__4 IS NULL)) )
  </code></pre>
  
  <p>(long list of columns replaced with asterisk and parameters declared at top, but it does not matter)</p>
  
  <p>This query works very slow with complicated query plan (~20 seconds). If I comment this condition at end of query:</p>
  
  <pre><code> /*OR (([Extent2].[Uid] IS NULL) AND (@p__linq__4 IS NULL))*/
  </code></pre>
  
  <p>it run with lightning speed (few milliseconds). Extent2 is DocumentFile, column Uid is primary key and it never be <code>NULL</code>.</p>
  
  <p>In C# code column Uid declared as Guid:</p>
  
  <pre><code>public class DocumentFile
  {
      public const string EntityType = "DocumentFile";
  
      [Key]
      public Guid Uid { get; set; }
  
      public Guid DocumentUid { get; set; }
      ...
  }
  </code></pre>
  
  <p>How to fix query or tell SQL Server to use simple query plan, like for query with commented condition?</p>