efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Query :: invalid sql generated when performing query with include

Open maumar opened this issue 12 years ago • 6 comments

Repro is as follows:

    public class Gear
    {
        public Gear()
        {
            Weapons = new List<Weapon>();
        }

        // composite key
        public string Nickname { get; set; }
        public int SquadId { get; set; }

        public string FullName { get; set; }

        public virtual Squad Squad { get; set; }

        // TODO: make this many to many - not supported at the moment
        public virtual ICollection<Weapon> Weapons { get; set; }

        public string LeaderNickname { get; set; }
        public int LeaderSquadId { get; set; }
    }

    public class Squad
    {
        public Squad()
        {
            Members = new List<Gear>();
        }

        // non-auto generated key
        public int Id { get; set; }
        public string Name { get; set; }

        // auto-generated non-key (sequence)
        public int InternalNumber { get; set; }

        public virtual ICollection<Gear> Members { get; set; }
    }

    public class Weapon
    {
        // auto generated key (sequence) TODO: make nullable when issue #478 is fixed
        public int Id { get; set; }
        public string Name { get; set; }

        // 1 - 1 self reference
        public int? SynergyWithId { get; set; }
        public virtual Weapon SynergyWith { get; set; }

        public string OwnerNickname { get; set; }
        public int OwnerSquadId { get; set; }
        public Gear Owner { get; set; }

    }

    public class GearOfWarContext : DbContext
    {
        public DbSet<Gear> Gears { get; set; }
        public DbSet<Squad> Squads { get; set; }
        public DbSet<Weapon> Weapons { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {

            builder.Entity<Gear>().Key(g => new { g.Nickname, g.SquadId });

            builder.Entity<Squad>().Key(s => s.Id);
            builder.Entity<Squad>().OneToMany(s => s.Members, g => g.Squad).ForeignKey(g => g.SquadId);
            builder.Model.GetEntityType(typeof(Squad)).GetProperty("Id").ValueGeneration = ValueGeneration.OnAdd;

            builder.Entity<Weapon>().OneToOne(w => w.SynergyWith).ForeignKey<Weapon>(w => w.SynergyWithId);
            builder.Entity<Weapon>().ManyToOne(w => w.Owner, g => g.Weapons).ForeignKey(w => new { w.OwnerNickname, w.OwnerSquadId });
        }

        protected override void OnConfiguring(DbContextOptions options)
        {
            options.UseSqlServer(@"Server=.\SQLEXPRESS;Database=Repro926;Trusted_Connection=True;MultipleActiveResultSets=true");
        }
    }

    public class DatabaseSeeder
    {
        public void SeedDatabase(GearOfWarContext ctx)
        {
            var deltaSquad = new Squad
            {
                Name = "Delta",
                Members = new List<Gear>(),
            };

            ctx.Squads.Add(deltaSquad);
            ctx.SaveChanges();

            var marcusLancer = new Weapon
            {
                Name = "Marcus' Lancer",
            };

            var marcusGnasher = new Weapon
            {
                Name = "Marcus' Gnasher",
                SynergyWith = marcusLancer,
            };

            ctx.Weapons.AddRange(new[] { marcusLancer, marcusGnasher });
            ctx.SaveChanges();

            var marcus = new Gear
            {
                Nickname = "Marcus",
                FullName = "Marcus Fenix",
                SquadId = deltaSquad.Id,
                Weapons = new List<Weapon> { marcusLancer, marcusGnasher },
            };

            ctx.Gears.AddRange(new[] { marcus, });
            ctx.SaveChanges();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (var ctx = new GearOfWarContext())
            {
                ctx.Database.EnsureDeleted();
                ctx.Database.EnsureCreated();
                new DatabaseSeeder().SeedDatabase(ctx);

                var query = ctx.Gears.Include(g => g.Weapons).ToList();

            }
        }
    }

Following query gets generated:

SELECT [w].[Id], [w].[Name], [w].[OwnerNickname], [w].[OwnerSquadId], [w].[SynergyWithId] FROM [Weapon] AS [w] INNER JOIN ( SELECT DISTINCT [g].[Nickname], [g].[SquadId] FROM [Gear] AS [g] ) AS [g] ON ([w].[Nickname] = [g].[OwnerNickname] AND [w].[SquadId] = [g].[OwnerSquadId]) ORDER BY [g].[Nickname], [g].[SquadId]

and it should be:

SELECT [w].[Id], [w].[Name], [w].[OwnerNickname], [w].[OwnerSquadId], [w].[SynergyWithId] FROM [Weapon] AS [w] INNER JOIN ( SELECT DISTINCT [g].[Nickname], [g].[SquadId] FROM [Gear] AS [g] ) AS [g] ON ([g].[Nickname] = [w].[OwnerNickname] AND [g].[SquadId] = [w].[OwnerSquadId]) ORDER BY [g].[Nickname], [g].[SquadId]

([g] and [w] aliases should be switched around in the join predicate)

maumar avatar Oct 21 '14 03:10 maumar

fixed

maumar avatar Oct 23 '14 22:10 maumar

Not all providers support DISTINCT. In Google Big Query the error message is: syntax error at: 4.7 - 4.58. SELECT DISTINCT is currently not supported. Please use GROUP BY instead to get the same effect. [400] Is it possible to override code generation to fix this problem?

Aristarh71 avatar Oct 06 '15 15:10 Aristarh71

Provider for Google Big Query is here: https://github.com/DevExpress/BigQueryProvider

Aristarh71 avatar Oct 06 '15 15:10 Aristarh71

@Aristarh71 provider could override DefaultQuerySqlGenerator.VisitSelect to generate SELECT that works on their backend as a workaround.

maumar avatar Oct 06 '15 18:10 maumar

VisitSelect in DefaultQuerySqlGenerator contains some private method calls and classes and too large. VisitJoin method is private (is it possible to make it protected?). Private class NullComparisonTransformingVisitor is used too. Field _parameterValues is inaccessible (private).

Aristarh71 avatar Oct 07 '15 07:10 Aristarh71

I opened issue to track this https://github.com/aspnet/EntityFramework/issues/3366

maumar avatar Oct 07 '15 18:10 maumar