Skip to content

Query: Select after complex GroupJoin leads to unpredictable results #4858

Closed

Description

@yyjdelete

Database: MSSQL
EntityFramework: EntityFramework.Core:7.0.0-rc1-final and Microsoft.EntityFrameworkCore:1.0.0-rc2-20261(aspnetcidev)

ctx.DeviceMsgUps
     .GroupJoin(ctx.UserDeviceMaps.Where(udp => udp.UserId == 1025 && udp.Status == 0 && udp.DeviceId != null), dmu => dmu.DeviceId, udp => udp.DeviceId, (key, vals) => new { key, vals })
     .Where(pair => pair.vals.Any())
     .Select(pair=>pair.key)
     .Select(key=>new { key.Format })
     .Count()

Get 3 result(the same with ToList).


ctx.DeviceMsgUps
     .GroupJoin(ctx.UserDeviceMaps.Where(udp => udp.UserId == 1025 && udp.Status == 0 && udp.DeviceId != null), dmu => dmu.DeviceId, udp => udp.DeviceId, (key, vals) => new { key, vals })
     .Where(pair => pair.vals.Any())
     .Select(pair=>pair.key)
     //.Select(key=>new { key.Format })
     .Count()

Get 57 result(the same with ToList).


ctx.DeviceMsgUps
     .GroupJoin(ctx.UserDeviceMaps.Where(udp => udp.UserId == 1025 && udp.Status == 0 && udp.DeviceId != null), dmu => dmu.DeviceId, udp => udp.DeviceId, (key, vals) => new { key, vals })
     .Where(pair => pair.vals.Any())
     //.Select(pair=>pair.key)
     //.Select(key=>new { key.Format })
     .Count()

Get 1 result(the same with ToList).


Model

    [System.CodeDom.Compiler.GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.18.1.0")]
    public class DeviceMsgUp
    {
        public int MessageId { get; set; } // Message_ID (Primary key)
        public int DeviceId { get; set; } // Device_ID
        public byte Format { get; set; } // Format
        public byte Action { get; set; } // Action
        public string Data { get; set; } // Data (length: 1000)
        public System.DateTime? ExpireTime { get; set; } // Expire_Time
        public System.DateTime Update { get; set; } // Update
        public byte ResultStatus { get; set; } // Result_Status
        public string ResultData { get; set; } // Result_Data (length: 1000)
    }

    [System.CodeDom.Compiler.GeneratedCodeAttribute("EF.Reverse.POCO.Generator", "2.18.1.0")]
    public partial class UserDeviceMap
    {
        public int UdMapId { get; set; } // UDMap_ID (Primary key)
        public int UserId { get; set; } // User_ID
        public int? DeviceId { get; set; } // Device_ID
        public int? StudentId { get; set; } // Student_ID
        public int? ClassId { get; set; } // Class_ID
        public string NickName { get; set; } // Nick_Name (length: 20)
        public string Image { get; set; } // Image (length: 50)
        public bool? Gender { get; set; } // Gender
        public System.DateTime? BirthDate { get; set; } // Birth_Date
        public System.DateTime? BindDate { get; set; } // Bind_Date
        public byte Status { get; set; } // Status
        public int Creator { get; set; } // Creator
        public System.DateTime Upload { get; set; } // Upload
        public int Login { get; set; } // Login
        public System.DateTime Update { get; set; } // Update
        public string CellPhoneNum { get; set; } // CellPhoneNum (length: 11)

        // Reverse navigation
        public virtual System.Collections.Generic.ICollection<UserWalkTarget> UserWalkTargets { get; set; } // Many to many mapping

        // Foreign keys
        public virtual Class Class { get; set; } // FK_User_Device_Map_Class_ID_Class_Class_ID
        public virtual Device Device { get; set; } // FK_User_Device_Map_Device_ID_Device_Device_ID
        public virtual Role Role { get; set; } // FK_User_Device_Map_User_ID_Role_Role_ID
        public virtual Student Student { get; set; } // FK_User_Device_Map_Student_ID_Student_Student_ID

        public UserDeviceMap()
        {
            UserWalkTargets = new System.Collections.Generic.List<UserWalkTarget>();
        }
    }

Activity

  1. added this to the 1.0.0 milestone on Mar 25, 2016
  2. yyjdelete commented on Apr 9, 2016

    @yyjdelete
    Author

    I paste an test code for both at #4860 (comment)

  3. mikary commented on Apr 12, 2016

    @mikary
    Contributor

    This appears to be a bug (or multiple bugs) with the shape of the result from GroupJoin. I restructured the sample to something closer to what we use in QueryTestBase to compare the EF results with linq-to-objects. Note that the reference implementation has two results for each query.

        public class ComplexGroupJoin
        {
            [Fact]
            public void Group_join_without_projection()
            {
                AssertQuery(
                    (dmus, udms) => dmus
                        .GroupJoin(
                            udms.Where(udp => udp.UserId == 1025 && udp.DeviceId != null),
                            dmu => dmu.DeviceId,
                            udp => udp.DeviceId,
                            (key, vals) => new { key, vals })
                        .Where(pair => pair.vals.Any()),
                    asserter:
                        (l2oResults, efResults) =>
                            {
                                var l2oObjects
                                    = l2oResults
                                        .OfType<object[]>()
                                        .Select(o => o.Select(o2 =>
                                            new
                                            {
                                                Key = GetProperty<DeviceMsgUp>(o2, "key"),
                                                Vals = string.Join(", ", GetProperty<IEnumerable<UserDeviceMap>>(o2, "vals")
                                                    .Select(dum => dum.UdMapId.ToString()))
                                            }));
    
                                var efObjects
                                    = efResults
                                        .OfType<object[]>()
                                        .Select(o => o.Select(o2 =>
                                            new
                                            {
                                                Key = GetProperty<DeviceMsgUp>(o2, "key"),
                                                Vals = string.Join(", ", GetProperty<IEnumerable<UserDeviceMap>>(o2, "vals")
                                                    .Select(dum => dum.UdMapId.ToString()))
                                            }));
    
                                Assert.Equal(l2oObjects, efObjects);
                            });
    
                // Expected: WhereSelectEnumerableIterator<Object[], IEnumerable<<>f__AnonymousType10<DeviceMsgUp, String>>> [[{ Key = DeviceMsgUp 1, Vals = 1 }, { Key = DeviceMsgUp 2, Vals = 1 }]]
                // Actual:   WhereSelectEnumerableIterator<Object[], IEnumerable<<>f__AnonymousType10<DeviceMsgUp, String>>> [[{ Key = DeviceMsgUp 1, Vals = 1, 1 }]]
            }
    
            [Fact]
            public void Group_join_with_key_projection()
            {
                AssertQuery(
                    (dmus, udms) => dmus
                        .GroupJoin(
                            udms.Where(udp => udp.UserId == 1025 && udp.DeviceId != null),
                            dmu => dmu.DeviceId,
                            udp => udp.DeviceId,
                            (key, vals) => new { key, vals })
                        .Where(pair => pair.vals.Any())
                        .Select(pair => pair.key),
                    asserter:
                        (l2oResults, efResults) =>
                            {
                                var l2oObjects
                                    = l2oResults
                                        .OfType<object[]>()
                                        .Select(o => o.Select(o2 => (DeviceMsgUp)o2));
    
                                var efObjects
                                    = efResults
                                        .OfType<object[]>()
                                        .Select(o => o.Select(o2 => (DeviceMsgUp)o2));
    
                                Assert.Equal(l2oObjects, efObjects);
                            });
                // Expected: WhereSelectEnumerableIterator<Object[], IEnumerable<DeviceMsgUp>> [[DeviceMsgUp 1, DeviceMsgUp 2]]
                // Actual:   WhereSelectEnumerableIterator<Object[], IEnumerable<DeviceMsgUp>> [[DeviceMsgUp 1, DeviceMsgUp 2, DeviceMsgUp 3]]
            }
    
            [Fact]
            public void Group_join_with_key_action_projection()
            {
                AssertQuery(
                    (dmus, udms) => dmus
                        .GroupJoin(
                            udms.Where(udp => udp.UserId == 1025 && udp.DeviceId != null),
                            dmu => dmu.DeviceId,
                            udp => udp.DeviceId,
                            (key, vals) => new { key, vals })
                        .Where(pair => pair.vals.Any())
                        .Select(pair => pair.key)
                        .Select(key => new { key.Action }),
                    asserter:
                        (l2oResults, efResults) =>
                            {
                                var l2oObjects
                                    = l2oResults
                                        .OfType<object[]>()
                                        .Select(o => o.Select(o2 => GetProperty<byte>(o2, "Action")));
    
                                var efObjects
                                    = efResults
                                        .OfType<object[]>()
                                        .Select(o => o.Select(o2 => GetProperty<byte>(o2, "Action")));
    
                                Assert.Equal(l2oObjects, efObjects);
                            });
                // Passes (Probably by coincidence.)
            }
    
            #region test_setup
    
            public ComplexGroupJoin()
            {
                using (var context = new MyDbContext())
                {
                    context.Database.EnsureDeleted();
                    context.Database.EnsureCreated();
    
                    context.UserDeviceMaps.AddRange(_userDeviceMaps);
                    context.DeviceMsgUps.AddRange(_deviceMsgUps);
    
                    context.SaveChanges();
                }
            }
    
            private readonly List<DeviceMsgUp> _deviceMsgUps
                = new List<DeviceMsgUp>
                {
                    new DeviceMsgUp
                    {
                        MessageId = 1,
                        DeviceId = 1,
                        Action = 27,
                    },
                    new DeviceMsgUp
                    {
                        MessageId = 2,
                        DeviceId = 1,
                        Action = 27,
                    },
                    new DeviceMsgUp
                    {
                        MessageId = 3,
                        DeviceId = 2,
                        Action = 27,
                    }
                };
    
            private readonly List<UserDeviceMap> _userDeviceMaps
                = new List<UserDeviceMap>
                {
                    new UserDeviceMap
                    {
                        UdMapId = 1,
                        UserId = 1025,
                        DeviceId = 1
                    }
                };
    
            private static T GetProperty<T>(object o, string propertyName)
                => (T)o.GetType().GetProperty(propertyName).GetValue(o);
    
            private void AssertQuery(
                Func<IQueryable<DeviceMsgUp>, IQueryable<UserDeviceMap>, IQueryable<object>> query,
                bool assertOrder = false,
                Action<IList<object>, IList<object>> asserter = null)
            {
                using (var context = new MyDbContext())
                {
                    TestHelpers.AssertResults(
                        new[] { query(_deviceMsgUps.AsQueryable(), _userDeviceMaps.AsQueryable()).ToArray() },
                        new[] { query(context.Set<DeviceMsgUp>(), context.Set<UserDeviceMap>()).ToArray() },
                        assertOrder,
                        asserter);
                }
            }
    
            #endregion
    
            #region model
    
            public class MyDbContext : DbContext
            {
                public DbSet<DeviceMsgUp> DeviceMsgUps { get; set; }
                public DbSet<UserDeviceMap> UserDeviceMaps { get; set; }
    
                protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
                {
                    base.OnConfiguring(optionsBuilder);
                    optionsBuilder.UseSqlServer("Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=ConfusingErrorTest;Integrated Security=True");
                }
    
                protected override void OnModelCreating(ModelBuilder modelBuilder)
                {
                    modelBuilder.Entity<UserDeviceMap>()
                        .HasKey(udm => udm.UdMapId);
                    modelBuilder.Entity<UserDeviceMap>()
                        .Property(udm => udm.UdMapId).ValueGeneratedNever();
    
                    modelBuilder.Entity<DeviceMsgUp>()
                        .HasKey(dmu => dmu.MessageId);
                    modelBuilder.Entity<DeviceMsgUp>()
                        .Property(dmu => dmu.MessageId).ValueGeneratedNever();
                }
            }
    
            public class DeviceMsgUp
            {
                public int MessageId { get; set; } //(Primary key)
                public int DeviceId { get; set; }
                public byte Action { get; set; }
    
                protected bool Equals(DeviceMsgUp other) => string.Equals(MessageId, other.MessageId);
    
                public override bool Equals(object obj)
                {
                    if (ReferenceEquals(null, obj))
                    {
                        return false;
                    }
                    if (ReferenceEquals(this, obj))
                    {
                        return true;
                    }
    
                    return obj.GetType() == GetType()
                           && Equals((DeviceMsgUp)obj);
                }
    
                public override int GetHashCode() => MessageId.GetHashCode();
    
                public override string ToString() => "DeviceMsgUp " + MessageId;
            }
    
            public class UserDeviceMap
            {
                public int UdMapId { get; set; } //(Primary key)
                public int UserId { get; set; }
                public int? DeviceId { get; set; }
    
                protected bool Equals(UserDeviceMap other) => string.Equals(UdMapId, other.UdMapId);
    
                public override bool Equals(object obj)
                {
                    if (ReferenceEquals(null, obj))
                    {
                        return false;
                    }
                    if (ReferenceEquals(this, obj))
                    {
                        return true;
                    }
    
                    return obj.GetType() == GetType()
                           && Equals((UserDeviceMap)obj);
                }
    
                public override int GetHashCode() => UdMapId.GetHashCode();
    
                public override string ToString() => "Customer " + UdMapId;
            }
    
            #endregion
        }
  4. mikary commented on Apr 12, 2016

    @mikary
    Contributor

    Clearing milestone for triage

  5. removed this from the 1.0.0 milestone on Apr 12, 2016
  6. added this to the 1.0.0 milestone on Apr 15, 2016
  7. 8 remaining items

  8. added a commit that references this issue on Aug 24, 2016
  9. changed the title [-]Select after complex GroupJoin lead to unpredictable result?[/-] [+]Select after complex GroupJoin lead to unpredictable result[/+] on Aug 24, 2016
  10. added this to the 1.0.1 milestone on Aug 25, 2016
  11. Eilon commented on Aug 26, 2016

    @Eilon
    Contributor

    Approved for 1.0.1.

  12. added a commit that references this issue on Aug 27, 2016
  13. maumar commented on Aug 27, 2016

    @maumar
    Contributor

    Fixed in: e514b49 (1.0.1) 1a46a54 (dev)

  14. changed the title [-]Select after complex GroupJoin lead to unpredictable result[/-] [+]Query: Select after complex GroupJoin lead to unpredictable result[/+] on Sep 13, 2016
  15. changed the title [-]Query: Select after complex GroupJoin lead to unpredictable result[/-] [+]Query: Select after complex GroupJoin leads to unpredictable results[/+] on Sep 13, 2016
  16. 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

No labels
No labels

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions