Skip to content

Query Perf: Selecting entire table for navigation properties in projections #5738

Closed

Description

@ruchanb

Steps to reproduce

public class Country
{        
    public string CountryCode { get; set; }
    public string CountryName { get; set; }
    public virtual ICollection<State> States { get; set; }
}

public class State 
{
    public string StateCode { get; set; }
    public string StateName { get; set; }
    public string CountryCode { get; set; }       
    public Country Country { get; set; }
}

Mapping on Country

builder.ToTable("Country");
builder.HasKey(pr => pr.CountryCode);
builder.HasMany(m => m.States).WithOne(i => i.Country).HasForeignKey(m => m.CountryCode);

Mapping on State

builder.ToTable("State");
builder.HasKey(pr => pr.StateCode);
builder.HasOne(m => m.Country).WithMany(m => m.States).HasForeignKey(m => m.CountryCode);

Now the Query

var query = _context.Countries
                    .Where(i => i.CountryCode == "USA")
                    .Select(m => new
                                  {
                                       m.CountryName,
                                       m.CountryCode,
                                       States = m.States.Select(x => new
                                                         {
                                                            x.StateCode,
                                                            x.StateName,
                                                            x.CountryCode
                                                         })
                                  }).AsQueryable();
  return query.ToList();

The issue

When I run SQL Profiler on this query I get following

SELECT [i].[CountryName], [i].[CountryCode]
FROM [Country] AS [i]
WHERE [i].[CountryCode] = N'USA'

and

SELECT [x].[CountryCode], [x].[StateCode], [x].[StateName]
FROM [State] AS [x]

I understand the two queries are not combined as in previous versions of EntityFramework. However, here the query on State is just select all without any where condition from the Country it is looking for. It does gives me States from 'USA' but it is doing so in the memory, not the SQL server.

Now make the query to include about 5 countries, it gives me 5 of these queries without any condition for Country

SELECT [x].[CountryCode], [x].[StateCode], [x].[StateName]
FROM [State] AS [x]

Further technical details

EF Core version: 1.0.0-rc2-final
Operating system: Windows 10
SQL Server 2008
Visual Studio version: VS 2015 update 2
Framework Target: net461

Activity

  1. rowanmiller commented on Jun 13, 2016

    @rowanmiller
    Contributor

    @anpete @maumar is this already tracked by another issue?

  2. maumar commented on Jun 13, 2016

    @maumar
    Contributor

    Related to #4007

  3. ruchanb commented on Jun 14, 2016

    @ruchanb
    Author

    Is this a bug or work in progress?

  4. rowanmiller commented on Jun 15, 2016

    @rowanmiller
    Contributor

    Closing as a dupe

  5. changed the title [-]Linq to SQL on relation[/-] [+]Query: Generating unfiltered navigation property projections[/+] on Jun 21, 2016
  6. rowanmiller commented on Jun 21, 2016

    @rowanmiller
    Contributor

    Reopening as we are going to track the lack of filtering issue separately from the n+1 optimization.

  7. anpete commented on Jun 21, 2016

    @anpete
    Contributor
  8. changed the title [-]Query: Generating unfiltered navigation property projections[/-] [+]Query: Selecting entire table for navigation properties in projections[/+] on Jun 21, 2016
  9. added this to the 1.0.1 milestone on Jun 21, 2016
  10. gdoron commented on Jun 21, 2016

    @gdoron

    Don't get me wrong, I really appreciate the team's hard work and all.
    But EF might get the RTM title in couple of days, but it's not there yet.
    A trivial query resulting in a full table retrieval, that's not RTM.

    Many things have changed to the best in Microsoft in the last couple of years, including the open source and multi platform change, but "version 1 isn't reliable - wait for SP1" hasn't.
    😢

  11. 11 remaining items

  12. modified the milestones: 1.1.0, 1.0.1 on Jul 8, 2016
  13. rowanmiller commented on Jul 8, 2016

    @rowanmiller
    Contributor

    Realocating to 1.1.0 as the fix for this was pretty high risk.

  14. maumar commented on Jul 8, 2016

    @maumar
    Contributor

    fixed in #6022, merged to dev in 0669372

  15. gdoron commented on Jul 9, 2016

    @gdoron

    @rowanmiller Thanks for the fix and the update!
    Is there an estimation on when 1.1.0 will be released?
    The roadmap hasn't been updated for a month.

  16. ruchanb commented on Sep 12, 2016

    @ruchanb
    Author

    I used 1.1.0-alpha1-22107 and see no change in the query.

  17. maumar commented on Sep 20, 2016

    @maumar
    Contributor

    @ruchanb I just run the following code:

        class Program
        {
            static void Main(string[] args)
            {
                using (var ctx = new MyContext())
                {
                    ctx.Database.EnsureDeleted();
                    ctx.Database.EnsureCreated();
    
                    var s11 = new State { CountryCode = "USA", StateCode = "WA", StateName = "Washington" };
                    var s12 = new State { CountryCode = "USA", StateCode = "CA", StateName = "California" };
                    var s21 = new State { CountryCode = "PL", StateCode = "DS", StateName = "Dolnoslaskie" };
    
                    var c1 = new Country { CountryCode = "USA", CountryName = "United States", States = new List<State> { s11, s12 } };
                    var c2 = new Country { CountryCode = "PL", CountryName = "Poland", States = new List<State> { s21 } };
    
                    ctx.States.AddRange(s11, s12, s21);
                    ctx.Countries.AddRange(c1, c2);
                    ctx.SaveChanges();
                }
    
                using (var ctx = new MyContext())
                {
                    var query = ctx.Countries
                        .Where(i => i.CountryCode == "USA")
                        .Select(m => new
                        {
                            m.CountryName,
                            m.CountryCode,
                            States = m.States.Select(x => new
                            {
                                x.StateCode,
                                x.StateName,
                                x.CountryCode
                            })
                        }).AsQueryable();
                    var result = query.ToList();
                    foreach (var r in result)
                    {
                        var foo = r.States.ToList();
                        Console.WriteLine(foo);
                    }
                }
            }
        }
    
        public class Country
        {
            public string CountryCode { get; set; }
            public string CountryName { get; set; }
            public virtual ICollection<State> States { get; set; }
        }
    
        public class State
        {
            public string StateCode { get; set; }
            public string StateName { get; set; }
            public string CountryCode { get; set; }
            public Country Country { get; set; }
        }
    
        public class MyContext : DbContext
        {
            public DbSet<Country> Countries { get; set; }
            public DbSet<State> States { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer("Server=.;Database=Repro5738;Trusted_Connection=True;MultipleActiveResultSets=true");
            }
    
            protected override void OnModelCreating(ModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Country>(b =>
                {
                    b.ToTable("Country");
                    b.HasKey(pr => pr.CountryCode);
                    b.HasMany(m => m.States).WithOne(i => i.Country).HasForeignKey(m => m.CountryCode);
                });
    
                modelBuilder.Entity<State>(b =>
                {
                    b.ToTable("State");
                    b.HasKey(pr => pr.StateCode);
                    b.HasOne(m => m.Country).WithMany(m => m.States).HasForeignKey(m => m.CountryCode);
                });
            }
        }
    

    on our nightly build and got this (expected) sql:

    SELECT [i].[CountryName], [i].[CountryCode]
    FROM [Country] AS [i]
    WHERE [i].[CountryCode] = N'USA'
    
    exec sp_executesql N'SELECT [x].[StateCode], [x].[StateName], [x].[CountryCode]
    FROM [State] AS [x]
    WHERE @_outer_CountryCode = [x].[CountryCode]',N'@_outer_CountryCode nvarchar(450)',@_outer_CountryCode=N'USA'
    

    Is there any difference between the code you have and the one above?

  18. ruchanb commented on Sep 21, 2016

    @ruchanb
    Author

    Hmm, I tried your code and the sql seems to be as you said. What about the no of queries on State though? State is queried each time as the no of countries listed..
    Thanks.

  19. maumar commented on Sep 21, 2016

    @maumar
    Contributor

    @ruchanb N+1 queries for top level collections is tracked here: #4007

    this fix aimed to mitigate it somewhat by only pulling in relevant entities, rather than entire DbSets

  20. modified the milestones: , 1.1.0 on Oct 15, 2022
  21. added theissue type on Jun 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions