efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Multiple Where method calls on one IQueryable, only the last one generates SQL statement.

Open RickyLin opened this issue 11 years ago • 7 comments

I assume it's a quite common situation that we need to call Where method multiple times on one IQueryable object. Code similar to this:

IQueryable<Customer> query = myDbContext.Customers;
if ( contactName != null )
    query = query.Where(c => c.ContactName == contactName);

if ( contactTitle != null )
    query = query.Where(c => c.ContactTitle == contactTitle);

Customer[] customers = query.ToArray();

I know I can convert the preceding code to this:

IQueryable<Customer> query = myDbContext.Customers.Where( c =>
    (contactName == null || c.ContactName == contactName)
    && (contactTitle == null || c.ContactTitle == contactTitle)
);

and EF 7 will generate SQL statement similar to this ( when contactName is not null but contactTitle is null):

WHERE (1 = 0 OR ContactName = @p0) AND ( 1 = 1 OR ContactTitle = NULL )

I don't thinks the generated SQL statement is ideal though. It would be better if we can support multiple Where method calls on one IQueryable and the preceding SQL statement would be just WHERE ContactName = @p0

It seems simple to get EF 7 support this feature, I have tried it out in my fork and it works. The problem is that how I should write test code for this feature? There are dozens of Where_* test methods in test projects, should I duplicate all of them and modify the duplicated test methods to call 2 or more Where methods?

RickyLin avatar Jan 18 '15 15:01 RickyLin

@RickyLin - Based on the SQL you included for the collapsed version of the query it looks like contactName was null (the 1 = 0 in the SQL indicates this). Can you confirm that this is not the reason that the Where method from the original logic is not being applied (since in your logic the Where(c => c.ContactName == contactName) won't get called if contactName is null).

rowanmiller avatar Jan 19 '15 19:01 rowanmiller

@rowanmiller - for the collapsed version of the query, the generated sql statement is correct. Here is an working example, running on regular Console Application, .NET Framework 4.5.1, EF 7 beta 2.

I think the sql statement generated by (3) is correct. The problem is (2), I want to create a pull request for this issue so for (2) EF can generate the correct sql statement WHERE WHERE [c].[ContactName] = @p0 AND [c].[ContactTitle] = @p1. However, as my first post said, I have no idea how to create test code for my modification in test projects. The modification I did to address this issue is quite simple.

using System;
using System.Linq;
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;

namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main(string[] args)
        {
            string contactName = null;
            string contactTitle = "CTO";
            using (NwDbContext context = new NwDbContext())
            {
                /* ------------------- First Query (1) ------------------ */

                IQueryable<Customer> query = context.Customers;
                if (contactName != null)
                    query = query.Where(c => c.ContactName == contactName);

                if (contactTitle != null)
                    query = query.Where(c => c.ContactTitle == contactTitle);

                Customer[] customers = query.ToArray();

                /* the sql statement generated by EF 7

exec sp_executesql N'SELECT [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[CustomerId]
FROM [Customers] AS [c]
WHERE [c].[ContactTitle] = @p0',N'@p0 nvarchar(3)',@p0=N'CTO'

                */

                /* ------------------- Next One (2) ------------------ */

                contactName = "Ricky";
                contactTitle = "Programmer";

                query = context.Customers;
                if (contactName != null)
                    query = query.Where(c => c.ContactName == contactName);

                if (contactTitle != null)
                    query = query.Where(c => c.ContactTitle == contactTitle);

                customers = query.ToArray();

                /* the sql statement generated by EF 7, there are 2 Where method calls, but only the last one appears in sql statement

exec sp_executesql N'SELECT [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[CustomerId]
FROM [Customers] AS [c]
WHERE [c].[ContactTitle] = @p0',N'@p0 nvarchar(10)',@p0=N'Programmer'

                */

                /* ------------------- Next One (3) ------------------ */

                contactName = null;
                contactTitle = "CTO";
                query = context.Customers.Where(c =>
                   (contactName == null || c.ContactName == contactName)
                   && (contactTitle == null || c.ContactTitle == contactTitle)
                );

                customers = query.ToArray();

                /* the sql statement generated by EF 7

exec sp_executesql N'SELECT [c].[CompanyName], [c].[ContactName], [c].[ContactTitle], [c].[CustomerId]
FROM [Customers] AS [c]
WHERE ((1 = 1 OR [c].[ContactName] IS NULL) AND (1 = 0 OR [c].[ContactTitle] = @p0))',N'@p0 nvarchar(3)',@p0=N'CTO'

                */
            }
            Console.ReadLine();
        }
    }

    public class NwDbContext : DbContext
    {
        public DbSet<Customer> Customers { get; set; }

        protected override void OnConfiguring(DbContextOptions options)
        {
            base.OnConfiguring(options);
            options.UseSqlServer("Data Source=10.4.30.42\\SqlExpress; Initial Catalog=Northwind; User Id=sx; Password=");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<Customer>().ForRelational().Table("Customers");
        }
    }

    public class Customer
    {
        public string CustomerId { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }
    }
}

RickyLin avatar Jan 20 '15 14:01 RickyLin

@RickyLin, you can add tests to Microsoft.Data.Entity.FunctionalTests.QueryTestBase and then assert the SQL in the derived test classes.

anpete avatar Jan 20 '15 18:01 anpete

@RickyLin , any progress on the fix ?

StevenVandenBroeck avatar Jan 26 '15 11:01 StevenVandenBroeck

@xytyx - The code has been done and tested in my little test project a few days ago but I'm not able to get EF tests run successfully. You may see my commit in my pull request created just now.

RickyLin avatar Jan 26 '15 16:01 RickyLin

the pull request for this has been merged. so I closed this issue.

RickyLin avatar Jan 30 '15 00:01 RickyLin

@rickylin thanks for the contribution!

divega avatar Jan 30 '15 02:01 divega