Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The multi-part identifier "XXX" could not be bound. after Take() in EF Core 3.1.0 #19947

Closed
MhozaifaA opened this issue Feb 16, 2020 · 15 comments
Assignees
Labels
area-query closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. customer-reported punted-for-5.0 type-bug
Milestone

Comments

@MhozaifaA
Copy link

MhozaifaA commented Feb 16, 2020

i saw this issue fixed ... but i still it in EF Core 3.1.0

The following code :

   Context.Users.
                    Where(captain => captain.Id == CaptainId).
                    Select(captain => new CaptainDetailsDto()
                    {


                        TaxiCount = TaxiCount,
                        Rate = Rate,
                        IsStop = IsStop,

                        CaptainDto = new CaptainDto() {
                            Id = CaptainId,
                            UserName = captain.UserName,
                          

                            SerialNumber = captain.SerialNumber,
                            FullName = captain.FullName,
                            SureName = captain.SureName,
                            MobileNumber = captain.MobileNumber,
                            DateOfBirth = captain.DateOfBirth,
                            NationalNumber = captain.NationalNumber,
                            AddressHome = captain.AddressHome,
                            CityId = captain.CityId,
                            PathPhotoCaptain = PhotoPath, 


                            CaptainCar = captain.Cars.Where(car => !car.DateDeleted.HasValue).Select(car => new CaptainCarDto()
                            {
                                LabelCar = car.LabelCar,
                                NumCard = car.NumCard,
                                CarLicenceType = car.CarLicenceType,
                                CarModelId = car.CarModelId,  
                                CarTypeId = car.CarTypeId,
                                DateOutCarLicence = car.DateOutCarLicence,
                                DateOutCarSecurta = car.DateOutCarSecurta,
                                Color = car.Color,
                                NoteCar = car.Note,
                                PathPhotoCar = car.Documents.
                                             FirstOrDefault(document => !document.DateDeleted.HasValue && document.Type == (int)DocumentTypes.CarPhoto).Path.OriginalString,
                            }).FirstOrDefault(),

                            Salary = captain.Sallaries.FirstOrDefault(sallary => !sallary.DateDeleted.HasValue && !sallary.DateChange.HasValue).Value,



                            PercentTaxi = captain.PercentTaxi,
                            InsuranceValue = captain.InsuranceValue,

                            PathFileCaptain = captain.Documents.
                                        FirstOrDefault(document0 => !document0.DateDeleted.HasValue && document0.Type == (int)DocumentTypes.UserFile).Path.OriginalString,

                            DateRegister = DateTime.Now,
                            //LastSeen

                            NoteCaptain = captain.Note,
                        },


                     
                        CaptainRateDtos = captain.Cars.Where(car0 => !car0.DateDeleted.HasValue). 
                                   SelectMany(car0 => car0.Taxis).
                                   Where(taxi => !taxi.DateDeleted.HasValue && (taxi.UserRate.HasValue || (taxi.UserTextRate != ""))).
                                   OrderByDescending(taxi => taxi.DateArrived ?? (taxi.DateCaptainArrived ?? taxi.DateRequest)).Take(12).
                                   Select(taxi => new CaptainRateDto()
                                   {
                                       Rate = taxi.UserRate.Value,
                                       UserRateText = taxi.UserTextRate,
                                       DateRate = taxi.DateArrived ?? (taxi.DateCaptainArrived ?? taxi.DateRequest),
                                       Name = taxi.UserEUser.FullName + " " + taxi.UserEUser.SureName,
                                       UserId = taxi.UserEUser.Id,
                                       PathUserPhoto = taxi.UserEUser.Documents.
                                           FirstOrDefault(document1 => !document1.DateDeleted.HasValue && document1.Type == (int)DocumentTypes.UserPhoto).Path.OriginalString
                                   }).ToList(),

                        ReportCount = captain.Cars.Where(car1 => !car1.DateDeleted.HasValue).
                                SelectMany(car1 => car1.Taxis).Count(taxi0 => !taxi0.DateDeleted.HasValue && taxi0.ReportText != null && taxi0.ReportText != ""),
                    
                        OwnerValue = 0,

                    }).SingleOrDefault();

Exception:

The multi-part identifier "t.UserEUserId" could not be bound.
The multi-part identifier "t.UserRate" could not be bound.
The multi-part identifier "t.UserTextRate" could not be bound.
The multi-part identifier "t.DateArrived" could not be bound.
The multi-part identifier "t.DateArrived" could not be bound.
The multi-part identifier "t.DateCaptainArrived" could not be bound.
The multi-part identifier "t.DateCaptainArrived" could not be bound.
The multi-part identifier "t.DateRequest" could not be bound.
The multi-part identifier "t.Id0" could not be bound.
The multi-part identifier "t.Id" could not be bound.
The multi-part identifier "t.c" could not be bound.

The Sql :

exec sp_executesql N'SELECT [t6].[UserName], [t6].[SerialNumber], [t6].[FullName], [t6].[SureName], [t6].[MobileNumber], [t6].[DateOfBirth], [t6].[NationalNumber], [t6].[AddressHome], [t6].[CityId], [t6].[LabelCar], [t6].[NumCard], [t6].[CarLicenceType], [t6].[CarModelId], [t6].[CarTypeId], [t6].[DateOutCarLicence], [t6].[DateOutCarSecurta], [t6].[Color], [t6].[Note], [t6].[Path], [t6].[c], [t6].[c0], [t6].[c1], [t6].[PercentTaxi], [t6].[InsuranceValue], [t6].[Path0], [t6].[c2], [t6].[c3], [t6].[Note0], [t6].[c4], [t6].[Id], [t11].[UserRate], [t11].[UserTextRate], [t11].[c], [t11].[c0], [t11].[Id], [t11].[Path], [t11].[c1], [t11].[Id0], [t11].[Id1]
FROM (
    SELECT TOP(2) [a].[UserName], [a].[SerialNumber], [a].[FullName], [a].[SureName], [a].[MobileNumber], [a].[DateOfBirth], [a].[NationalNumber], [a].[AddressHome], [a].[CityId], [t3].[LabelCar], [t3].[NumCard], [t3].[CarLicenceType], [t3].[CarModelId], [t3].[CarTypeId], [t3].[DateOutCarLicence], [t3].[DateOutCarSecurta], [t3].[Color], [t3].[Note], [t3].[Path], [t3].[c], [t3].[c0], (
        SELECT TOP(1) [s].[Value]
        FROM [Sallaries] AS [s]
        WHERE ([a].[Id] = [s].[EUserId]) AND ([s].[DateDeleted] IS NULL AND [s].[DateChange] IS NULL)) AS [c1], [a].[PercentTaxi], [a].[InsuranceValue], [t5].[Path] AS [Path0], [t5].[c] AS [c2], GETDATE() AS [c3], [a].[Note] AS [Note0], (
        SELECT COUNT(*)
        FROM [Cars] AS [c]
        INNER JOIN [Taxis] AS [t] ON [c].[Id] = [t].[CarId]
        WHERE (([a].[Id] = [c].[EUserId]) AND [c].[DateDeleted] IS NULL) AND (([t].[DateDeleted] IS NULL AND [t].[ReportText] IS NOT NULL) AND ([t].[ReportText] <> N''''))) AS [c4], [a].[Id]
    FROM [AspNetUsers] AS [a]
    LEFT JOIN (
        SELECT [t2].[LabelCar], [t2].[NumCard], [t2].[CarLicenceType], [t2].[CarModelId], [t2].[CarTypeId], [t2].[DateOutCarLicence], [t2].[DateOutCarSecurta], [t2].[Color], [t2].[Note], [t2].[Path], [t2].[c], [t2].[c0], [t2].[Id], [t2].[EUserId]
        FROM (
            SELECT [c0].[LabelCar], [c0].[NumCard], [c0].[CarLicenceType], [c0].[CarModelId], [c0].[CarTypeId], [c0].[DateOutCarLicence], [c0].[DateOutCarSecurta], [c0].[Color], [c0].[Note], [t1].[Path], [t1].[c], 1 AS [c0], [c0].[Id], [c0].[EUserId], ROW_NUMBER() OVER(PARTITION BY [c0].[EUserId] ORDER BY [c0].[Id]) AS [row]
            FROM [Cars] AS [c0]
            LEFT JOIN (
                SELECT [t0].[Path], [t0].[c], [t0].[Id], [t0].[CarId]
                FROM (
                    SELECT [d].[Path], 1 AS [c], [d].[Id], [d].[CarId], ROW_NUMBER() OVER(PARTITION BY [d].[CarId] ORDER BY [d].[Id]) AS [row]
                    FROM [Documents] AS [d]
                    WHERE [d].[DateDeleted] IS NULL AND ([d].[Type] = 1)
                ) AS [t0]
                WHERE [t0].[row] <= 1
            ) AS [t1] ON [c0].[Id] = [t1].[CarId]
            WHERE [c0].[DateDeleted] IS NULL
        ) AS [t2]
        WHERE [t2].[row] <= 1
    ) AS [t3] ON [a].[Id] = [t3].[EUserId]
    LEFT JOIN (
        SELECT [t4].[Path], [t4].[c], [t4].[Id], [t4].[EUserId]
        FROM (
            SELECT [d0].[Path], 1 AS [c], [d0].[Id], [d0].[EUserId], ROW_NUMBER() OVER(PARTITION BY [d0].[EUserId] ORDER BY [d0].[Id]) AS [row]
            FROM [Documents] AS [d0]
            WHERE [d0].[DateDeleted] IS NULL AND ([d0].[Type] = 3)
        ) AS [t4]
        WHERE [t4].[row] <= 1
    ) AS [t5] ON [a].[Id] = [t5].[EUserId]
    WHERE [a].[Id] = @__CaptainId_0
) AS [t6]
OUTER APPLY (
    SELECT [t].[UserRate], [t].[UserTextRate], COALESCE([t].[DateArrived], COALESCE([t].[DateCaptainArrived], [t].[DateRequest])) AS [c], ([a0].[FullName] + N'' '') + [a0].[SureName] AS [c0], [a0].[Id], [t10].[Path], [t10].[c] AS [c1], [t].[Id0], [t].[Id] AS [Id1], [t].[c] AS [c2]
    FROM (
        SELECT TOP(12) [t7].[Id], [t7].[BagValue], [t7].[BoxId], [t7].[CaptainRate], [t7].[CaptainTextRate], [t7].[CarId], [t7].[DateArrived], [t7].[DateBooked], [t7].[DateCaptainArrived], [t7].[DateDeleted], [t7].[DateRequest], [t7].[DisableText], [t7].[DiscountId], [t7].[Distance], [t7].[EndLatitude], [t7].[EndLongitude], [t7].[IsReportDeleted], [t7].[LocalLatitude], [t7].[LocalLongitude], [t7].[Number], [t7].[PercentTaxi], [t7].[ReportText], [t7].[RestValue], [t7].[StartLatitude], [t7].[StartLongitude], [t7].[Tax], [t7].[TaxiType], [t7].[Time], [t7].[UserEUserId], [t7].[UserRate], [t7].[UserTextRate], [t7].[Value], [c1].[Id] AS [Id0], COALESCE([t7].[DateArrived], COALESCE([t7].[DateCaptainArrived], [t7].[DateRequest])) AS [c]
        FROM [Cars] AS [c1]
        INNER JOIN [Taxis] AS [t7] ON [c1].[Id] = [t7].[CarId]
        WHERE (([t6].[Id] = [c1].[EUserId]) AND [c1].[DateDeleted] IS NULL) AND ([t7].[DateDeleted] IS NULL AND ([t7].[UserRate] IS NOT NULL OR (([t7].[UserTextRate] <> N'''') OR [t7].[UserTextRate] IS NULL)))
        ORDER BY COALESCE([t7].[DateArrived], COALESCE([t7].[DateCaptainArrived], [t7].[DateRequest])) DESC
    ) AS [t8]
    INNER JOIN [AspNetUsers] AS [a0] ON [t].[UserEUserId] = [a0].[Id]
    LEFT JOIN (
        SELECT [t9].[Path], [t9].[c], [t9].[Id], [t9].[EUserId]
        FROM (
            SELECT [d1].[Path], 1 AS [c], [d1].[Id], [d1].[EUserId], ROW_NUMBER() OVER(PARTITION BY [d1].[EUserId] ORDER BY [d1].[Id]) AS [row]
            FROM [Documents] AS [d1]
            WHERE [d1].[DateDeleted] IS NULL AND ([d1].[Type] = 0)
        ) AS [t9]
        WHERE [t9].[row] <= 1
    ) AS [t10] ON [a0].[Id] = [t10].[EUserId]
) AS [t11]
ORDER BY [t6].[Id], [t11].[c2] DESC, [t11].[Id0], [t11].[Id1], [t11].[Id]',N'@__CaptainId_0 int',@__CaptainId_0=11

The whole issue with CaptainRateDtos =aptain.Cars.Whe........

EF Core version: 3.1.0
Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
Target framework: (e.g. .NET Core 3.1)
Operating system:
IDE: (e.g. Visual Studio 2019 16.4.2)

@MhozaifaA
Copy link
Author

I fix it by but Take(12) after Select

@MhozaifaA MhozaifaA changed the title The multi-part identifier "XXX" could not be bound. The multi-part identifier "XXX" could not be bound. after Take in EF Core 3.1.0 Feb 16, 2020
@MhozaifaA MhozaifaA changed the title The multi-part identifier "XXX" could not be bound. after Take in EF Core 3.1.0 The multi-part identifier "XXX" could not be bound. after Take() in EF Core 3.1.0 Feb 16, 2020
@maumar
Copy link
Contributor

maumar commented Feb 18, 2020

possible dupe of #19763

@smitpatel
Copy link
Contributor

Does it work in master?

@ajcvickers
Copy link
Member

@maumar to try on master.

@MhozaifaA
Copy link
Author

the query will execute fine when fix aliases in SqlServer >>>> but in normal "Take" still make issue , not working as expected to master

@MhozaifaA
Copy link
Author

MhozaifaA commented Feb 21, 2020

.... any way thanks .. it's not big issue as i see .. and in default linq work after collection .... hope to solve it in EFCore mapping & fix aliases

@maumar
Copy link
Contributor

maumar commented Feb 24, 2020

@MhozaifaA can you provide code listing for all the entities used in the query as well contents of OnModelCreating method on your DbContext?

@maumar maumar self-assigned this Feb 24, 2020
@MhozaifaA
Copy link
Author

MhozaifaA commented Mar 1, 2020

@maumar .... Maybe it could be useful.... sorry for being late for the answer

users Table

 public class EUser : IdentityUser<int>
    {
        //  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]

        #region -   Constructor   -

        public EUser() //  null
        {
            Areas = new HashSet<Area>();
            Documents = new HashSet<Document>();
            Cars = new HashSet<Car>();
            Reports = new HashSet<Report>();
            Discounts = new HashSet<Discount>();
            Invites = new HashSet<Invite>();
            InvitedInvites = new HashSet<Invite>();
            Taxis = new HashSet<Taxi>();
            APIBoxs = new HashSet<Box>();
            Boxs = new HashSet<Box>();
            Stops= new HashSet<Stop>();
            Sallaries = new HashSet<Sallary>();
        }

        #endregion

        #region -   BaseEntity   -

        public DateTimeOffset? DateDeleted { get; set; }
        public bool IsDeleted => DateDeleted.HasValue;

        #endregion


        #region -   API   -

        // 
        [Column(TypeName = "int")]
        public int PolicyType { get; set; } // enum PolicyTypes



        [InverseProperty(nameof(Box.APIEUser))]
        public ICollection<Box> APIBoxs { get; set; }
        #endregion


        #region -   Share   -

        [Column(TypeName = "int")]
        [DefaultValue(0)]
        public int TypeAccount { get; set; }  // 0 API  , 1 Captain  , 2 User


        [Column(TypeName = "nvarchar(128)")]  // GUID  128
        public string SerialNumber { get; set; } //


        //[Required]
        [Column(TypeName = "nvarchar(100)")]
        public string FullName { get; set; } // 



        [Column(TypeName = "nvarchar(50)")]
        public string SureName { get; set; } // 



        //[Required]
        [Column(TypeName = "varchar(20)")]
       // [Index()]//  warrning..should be unique
        public string MobileNumber { get; set; } // 



        [Column(TypeName = "varchar(50)")]
        public string NationalNumber { get; set; } // 



        // datetime  1753yers to 9999yers 
        [Column(TypeName = "datetime2")] // here can set from "0001 / 01 / 01" to "9999 / 12 / 31" 
        public Nullable<DateTime> DateOfBirth { get; set; } // 


        [Column(TypeName = "datetime")]
        public Nullable<DateTime> DateRegister { get; set; } // 


        [Column(TypeName = "datetime")]
        public Nullable<DateTime> LastSeen { get; set; } // 


        [Column(TypeName = "nvarchar(max)")]
        public string Note { get; set; }    


        public ICollection<Area> Areas { get; set; }
        public ICollection<Document> Documents { get; set; }
        public ICollection<Report> Reports { get; set; }


        [InverseProperty(nameof(Box.EUser))]
        public ICollection<Box> Boxs { get; set; }




        #endregion


        #region -   Captain   -


        [Column(TypeName = "nvarchar(max)")]
        public string AddressHome { get; set; }// 



        //[Column(TypeName = "float")]
        //public Nullable<double> Salary { get; set; } // 


        [Column(TypeName = "varchar(20)")]
        public string PercentTaxi { get; set; } // 


        [Column(TypeName = "float")]
        public Nullable<double> InsuranceValue { get; set; } //  Token




        [Column(TypeName = "varchar(max)")]
        public string LastLatLong { get; set; }


        // [Column(TypeName = "decimal(max)")]
        // public DbGeography LastLatLong { get; set; }  // enough DECIMAL type

        //[Column(TypeName = "float")]
        //public decimal Latitude { get; set; }


        //[Column(TypeName = "float")]
        //public float Longitude { get; set; }


        // https://www.movable-type.co.uk/scripts/latlong-db.html            
        //The cosine law is:	d = acos(sin(φ1)⋅sin(φ2) + cos(φ1)⋅cos(φ2)⋅cos(Δλ) ) ⋅ R
        //                      where:	φ = latitude, λ = longitude(in radians)
        //                      R = radius of earth
        //                       d = distance between the points(in same units as R)

        //[Column(TypeName = "varchar(20)")]
        //public string NumJob { get; set; }  // 


        //[Column(TypeName = "datetime")]
        //public Nullable<DateTime> DateJob { get; set; }  // 


        //[Column(TypeName = "bit")]
        //public bool IsJob { get; set; } // 0  done   1 


        [Column(TypeName = "bit")]
        public bool IsActivated { get; set; } // 


        //[Column(TypeName = "int")]
        //public int CityWork { get; set; } // from Enum.Cities
        public Nullable<int> CityId { get; set; } //CityWork
        public City City { get; set; }


        public ICollection<Car> Cars { get; set; }

        public ICollection<Stop> Stops { get; set; }

        public ICollection<Sallary> Sallaries { get; set; }
        // 
        //[InverseProperty(nameof(Taxi.CaptainEUser))]
        //public ICollection<Taxi> CaptainTaxis { get; set; }

        #endregion


        #region -   user   -


        [Column(TypeName = "bit")]
        public bool IsBlocked { get; set; }


        public ICollection<Discount> Discounts { get; set; }


        [InverseProperty(nameof(Invite.EUser))]
        public ICollection<Invite> Invites { get; set; }


        [InverseProperty(nameof(Invite.InvitedEUser))]
        public ICollection<Invite> InvitedInvites { get; set; }


        public ICollection<Taxi> Taxis { get; set; }


        #endregion

    }

Taxi Table

 public class Taxi : BaseEntity
    {
        [Column(TypeName ="nvarchar(50)")]
        [Required]
        public string Number { get; set; }

        [Column(TypeName = "datetime")]
        public DateTime DateRequest { get; set; }


        [Column(TypeName = "datetime")]
        public Nullable<DateTime> DateCaptainArrived { get; set; }



        [Column(TypeName = "datetime")]
        public Nullable<DateTime> DateArrived { get; set; }


        [Column(TypeName = "datetime")]
        public Nullable<DateTime> DateBooked { get; set; }



        [Column(TypeName = "int")]
        public int TaxiType { get; set; } // enum TaxiTypes



        [Column(TypeName = "float")]
        public Nullable<double> StartLatitude { get; set; }


        [Column(TypeName = "float")]
        public Nullable<double> StartLongitude { get; set; }



        [Column(TypeName = "float")]
        public Nullable<double> EndLatitude { get; set; }


        [Column(TypeName = "float")]
        public Nullable<double> EndLongitude { get; set; }


        [Column(TypeName = "nvarchar(Max)")]
        public string LocalFrom { get; set; }

        [Column(TypeName = "nvarchar(Max)")]
        public string LocalDestination { get; set; }



        [Column(TypeName = "bigint")]
        public Nullable<long> Time { get; set; }


        [Column(TypeName = "float")]
        public Nullable<double> Distance { get; set; }


        [Column(TypeName = "int")]
        public Nullable<int> UserRate { get; set; }


        [Column(TypeName = "nvarchar(max)")]
        public string UserTextRate { get; set; }



        [Column(TypeName = "int")]
        public Nullable<int> CaptainRate { get; set; }


        [Column(TypeName = "nvarchar(max)")]
        public string CaptainTextRate { get; set; }



        [Column(TypeName = "float")]
        public Nullable<double> Value { get; set; } 
        // 



        [Column(TypeName = "float")]
        public Nullable<double> RestValue { get; set; } // 
        //   
        // 


        [Column(TypeName = "float")]
        public Nullable<double> BagValue { get; set; } //
        //  
        // 


        [Column(TypeName = "float")]
        public Nullable<double> Tax { get; set; } // 


        [Column(TypeName = "nvarchar(max)")]
        public string DisableText { get; set; }// 


        [Column(TypeName = "nvarchar(max)")]
        public string ReportText { get; set; } //

        [Column(TypeName = "bit")]
        public bool IsReportDeleted { get; set; } // 

        [Column(TypeName = "varchar(20)")]
        public string PercentTaxi { get; set; }// 


        public Nullable<int> DiscountId { get; set; }
        public Discount Discount { get; set; }


        [ForeignKey(nameof(UserEUser)), Column(Order = 1)]
        public int UserEUserId { get; set; }
        public EUser UserEUser { get; set; }  // 

        public Nullable<int> CarId { get; set; }
        public Car Car { get; set; }  // 

        //[ForeignKey(nameof(CaptainEUser)), Column(Order = 2)]
        //public Nullable<int> CaptainEUserId { get; set; }
        //public EUser CaptainEUser { get; set; }  // 


        public Nullable<int> BoxId { get; set; }
        public Box Box { get; set; }  // 


        public double CatchValue => Value ?? 0 - BagValue ?? 0 +
          ( RestValue != null ? (RestValue.Value < 0 ? 0 : RestValue.Value) : 0  ) - Distance ?? 0 + Tax ?? 0;

    }

Car Table

 public class Car :BaseEntity
    {
        public Car()
        {
            Documents = new HashSet<Document>();
            Taxis = new HashSet<Taxi>();
        }

        [Required]
        [Column(TypeName = "nvarchar(50)")]
        public string LabelCar { get; set; }



        [Column(TypeName = "int")]
        public int CarLicenceType { get; set; } // 



        [Column(TypeName = "datetime")]
        public Nullable<DateTime> DateOutCarLicence { get; set; } // 


        [Column(TypeName = "datetime")]
        public Nullable<DateTime> DateOutCarSecurta { get; set; } // 


        [Column(TypeName = "nvarchar(50)")] 
        public string NumCard { get; set; }// 


        [Column(TypeName = "char(9)")]
        //[DefaultValue("FFFFFF")]
        public string Color { get; set; }


        [Column(TypeName = "nvarchar(max)")]
        public string Note { get; set; }


        public int EUserId { get; set; }
        public EUser EUser { get; set; }

        public int CarModelId { get; set; }
        public CarModel CarModel { get; set; }

        public int CarTypeId { get; set; }
        public CarType CarType { get; set; }

        public ICollection<Document> Documents { get; set; }

        public ICollection<Taxi> Taxis { get; set; }
    }

DBContext..... i did't add OnModelCreating .... no need for me .for now

 public class ElCaptainDbContext : IdentityDbContext<EUser, ERole, int, EUserClaim, EUserRole
                                                     , EUserLogin, ERoleClaim, EUserToken>
    {


        #region -   Constructor   -
        public ElCaptainDbContext(DbContextOptions<ElCaptainDbContext> options) : base(options)
        {

        }

        #endregion


        #region -   Main   -

        public DbSet<Area> Areas { get; set; }

        public DbSet<Car> Cars { get; set; }

        public DbSet<CarModel> CarModels { get; set; }

        public DbSet<Document> Documents { get; set; }

        public DbSet<Invite> Invites { get; set; }

        public DbSet<Report> Reports { get; set; }

        public DbSet<Stop> Stops { get; set; }

        public DbSet<Sallary> Sallaries { get; set; }

        public DbSet<Taxi> Taxis { get; set; }


        #endregion


        #region -   Setting   -

        public DbSet<Ad> Ads { get; set; }

        public DbSet<Box> Boxes { get; set; }

        public DbSet<CarType> CarTypes { get; set; }

        public DbSet<City> Cities { get; set; }

        public DbSet<Discount> Discounts { get; set; }

        public DbSet<Job> Jobs { get; set; }

        public DbSet<Notification> Notifications { get; set; }

        public DbSet<Setting> Settings { get; set; }

        public DbSet<Tip> Tips { get; set; }

        #endregion



        //protected override void OnModelCreating(ModelBuilder modelBuilder)
        //{

        //    modelBuilder.Entity<ERole>().HasData( 
        //        new ERole { Id=1,Name="Admin"}
        //    );

        //    base.OnModelCreating(modelBuilder);

        //}

    }

I am sorry if my code was not professional

@maumar
Copy link
Contributor

maumar commented Mar 3, 2020

@MhozaifaA no worries. With the additional info you provided I was able to reproduce this issue.
@smitpatel it repros on current master as well.

@maumar
Copy link
Contributor

maumar commented Mar 3, 2020

Simplified repro:

        [ConditionalFact]
        public virtual void Repro19947()
        {
            using var ctx = new ElCaptainDbContext();
            ctx.Database.EnsureDeleted();
            ctx.Database.EnsureCreated();

            var query = ctx.Users.Select(captain => new
            {
                CaptainRateDtos = captain.Cars
                    .SelectMany(car0 => car0.Taxis)
                    .OrderByDescending(taxi => taxi.DateArrived).Take(12)
                    .Select(taxi => new
                    {
                        Rate = taxi.UserRate.Value,
                        UserRateText = taxi.UserTextRate,
                        UserId = taxi.UserEUser.Id,
                    }).ToList(),

                ReportCount = captain.Cars
                    .SelectMany(car1 => car1.Taxis).Count(taxi0 => taxi0.ReportText != ""),
            }).SingleOrDefault();
        }

        public class EUser 
        {
            public int Id { get; set; }

            public ICollection<Car> Cars { get; set; }
        }

        public class Taxi
        {
            public int Id { get; set; }
            public DateTime? DateArrived { get; set; }
            public int? UserRate { get; set; }
            public string UserTextRate { get; set; }
            public string ReportText { get; set; } 
            public EUser UserEUser { get; set; }  
        }

        public class Car
        {
            public int Id { get; set; }
            public ICollection<Taxi> Taxis { get; set; }
        }

        public class ElCaptainDbContext : DbContext
        {
            public DbSet<EUser> Users { get; set; }

            public DbSet<Car> Cars { get; set; }
            public DbSet<Taxi> Taxis { get; set; }

            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Repro19947;Trusted_Connection=True;MultipleActiveResultSets=true");
            }
        }

generated sql:

SELECT [t0].[c], [t0].[Id], [t3].[UserRate], [t3].[UserTextRate], [t3].[Id], [t3].[Id0], [t3].[Id00]
FROM (
    SELECT TOP(2) (
        SELECT COUNT(*)
        FROM [Cars] AS [c]
        INNER JOIN [Taxis] AS [t] ON [c].[Id] = [t].[CarId]
        WHERE ([u].[Id] = [c].[EUserId]) AND (([t].[ReportText] <> N'') OR [t].[ReportText] IS NULL)) AS [c], [u].[Id]
    FROM [Users] AS [u]
) AS [t0]
OUTER APPLY (
    SELECT [t].[UserRate], [t].[UserTextRate], [u0].[Id], [t].[Id] AS [Id0], [t].[Id0] AS [Id00], [t].[DateArrived]
    FROM (
        SELECT TOP(12) [c0].[Id], [c0].[EUserId], [t1].[Id] AS [Id0], [t1].[CarId], [t1].[DateArrived], [t1].[ReportText], [t1].[UserEUserId], [t1].[UserRate], [t1].[UserTextRate]
        FROM [Cars] AS [c0]
        INNER JOIN [Taxis] AS [t1] ON [c0].[Id] = [t1].[CarId]
        WHERE [t0].[Id] = [c0].[EUserId]
        ORDER BY [t1].[DateArrived] DESC
    ) AS [t2]
    LEFT JOIN [Users] AS [u0] ON [t].[UserEUserId] = [u0].[Id]
) AS [t3]
ORDER BY [t0].[Id], [t3].[DateArrived] DESC, [t3].[Id0], [t3].[Id00]

Sql exception:

The multi-part identifier "t.UserEUserId" could not be bound.
    The multi-part identifier "t.UserRate" could not be bound.
    The multi-part identifier "t.UserTextRate" could not be bound.
    The multi-part identifier "t.Id" could not be bound.
    The multi-part identifier "t.Id0" could not be bound.
    The multi-part identifier "t.DateArrived" could not be bound.

if Take call is removed, everything works fine, generating the following:

SELECT [t0].[c], [t0].[Id], [t2].[UserRate], [t2].[UserTextRate], [t2].[Id], [t2].[Id0], [t2].[Id1]
FROM (
    SELECT TOP(2) (
        SELECT COUNT(*)
        FROM [Cars] AS [c]
        INNER JOIN [Taxis] AS [t] ON [c].[Id] = [t].[CarId]
        WHERE ([u].[Id] = [c].[EUserId]) AND (([t].[ReportText] <> N'') OR [t].[ReportText] IS NULL)) AS [c], [u].[Id]
    FROM [Users] AS [u]
) AS [t0]
LEFT JOIN (
    SELECT [t1].[UserRate], [t1].[UserTextRate], [u0].[Id], [c0].[Id] AS [Id0], [t1].[Id] AS [Id1], [t1].[DateArrived], [c0].[EUserId]
    FROM [Cars] AS [c0]
    INNER JOIN [Taxis] AS [t1] ON [c0].[Id] = [t1].[CarId]
    LEFT JOIN [Users] AS [u0] ON [t1].[UserEUserId] = [u0].[Id]
) AS [t2] ON [t0].[Id] = [t2].[EUserId]
ORDER BY [t0].[Id], [t2].[DateArrived] DESC, [t2].[Id0], [t2].[Id1]

if projection 'ReportCount' is removed we generate the following:

SELECT [t].[Id], [t2].[UserRate], [t2].[UserTextRate], [t2].[Id], [t2].[Id0], [t2].[Id00]
FROM (
    SELECT TOP(2) [u].[Id]
    FROM [Users] AS [u]
) AS [t]
OUTER APPLY (
    SELECT [t].[UserRate], [t].[UserTextRate], [u0].[Id], [t].[Id] AS [Id0], [t].[Id0] AS [Id00], [t].[DateArrived]
    FROM (
        SELECT TOP(12) [c].[Id], [c].[EUserId], [t0].[Id] AS [Id0], [t0].[CarId], [t0].[DateArrived], [t0].[ReportText], [t0].[UserEUserId], [t0].[UserRate], [t0].[UserTextRate]
        FROM [Cars] AS [c]
        INNER JOIN [Taxis] AS [t0] ON [c].[Id] = [t0].[CarId]
        WHERE [t].[Id] = [c].[EUserId]
        ORDER BY [t0].[DateArrived] DESC
    ) AS [t1]
    LEFT JOIN [Users] AS [u0] ON [t].[UserEUserId] = [u0].[Id]
) AS [t2]
ORDER BY [t].[Id], [t2].[DateArrived] DESC, [t2].[Id0], [t2].[Id00]

which throws different error (invalid column)

@ajcvickers ajcvickers added this to the 5.0.0 milestone Mar 6, 2020
@ajcvickers ajcvickers assigned smitpatel and unassigned maumar Mar 6, 2020
@ajcvickers ajcvickers modified the milestones: 5.0.0, Backlog Jun 9, 2020
@smitpatel smitpatel removed their assignment Aug 27, 2020
@ajcvickers ajcvickers modified the milestones: Backlog, 6.0.0 Nov 5, 2020
@smitpatel smitpatel added the closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. label Mar 24, 2021
smitpatel added a commit that referenced this issue Mar 24, 2021
- Don't apply Include on entities with Include already applied
- Update table references when pushing down select into left for set operation
- Update identifiers after applying set operation if the projection removed exiting identifiers
- Update SQL references in pending collection during push down

Fix for the repro in #17337
Resolves #18738
Resolves #19763
Resolves #19947
Resolves #20813
Resolves #21026
Resolves #22222
Resolves #23676
Resolves #23720
smitpatel added a commit that referenced this issue Mar 24, 2021
- Don't apply Include on entities with Include already applied
- Update table references when pushing down select into left for set operation
- Update identifiers after applying set operation if the projection removed exiting identifiers
- Update SQL references in pending collection during push down

Fix for the repro in #17337
Resolves #18738
Resolves #19763
Resolves #19947
Resolves #20813
Resolves #21026
Resolves #22222
Resolves #23676
Resolves #23720
Resolves #24216
smitpatel added a commit that referenced this issue Mar 24, 2021
- Don't apply Include on entities with Include already applied
- Update table references when pushing down select into left for set operation
- Update identifiers after applying set operation if the projection removed exiting identifiers
- Update SQL references in pending collection during push down

Fix for the repro in #17337
Resolves #18738
Resolves #19763
Resolves #19947
Resolves #20813
Resolves #21026
Resolves #22222
Resolves #23676
Resolves #23720
Resolves #24216
smitpatel added a commit that referenced this issue Mar 25, 2021
- Don't apply Include on entities with Include already applied
- Update table references when pushing down select into left for set operation
- Update identifiers after applying set operation if the projection removed exiting identifiers
- Update SQL references in pending collection during push down

Fix for the repro in #17337
Resolves #18738
Resolves #19763
Resolves #19947
Resolves #20813
Resolves #21026
Resolves #22222
Resolves #23676
Resolves #23720
Resolves #24216
smitpatel added a commit that referenced this issue Mar 25, 2021
- Don't apply Include on entities with Include already applied
- Update table references when pushing down select into left for set operation
- Update identifiers after applying set operation if the projection removed exiting identifiers
- Update SQL references in pending collection during push down

Fix for the repro in #17337
Resolves #18738
Resolves #19763
Resolves #19947
Resolves #20813
Resolves #21026
Resolves #22222
Resolves #23676
Resolves #23720
Resolves #24216
@ajcvickers ajcvickers modified the milestones: 6.0.0, 6.0.0-preview4 Mar 25, 2021
@h0s
Copy link

h0s commented Apr 17, 2021

@ajcvickers is there any chance we get this fix for netcore 3.1 ? (package efcore 5.0 or 3.1.14)

@ajcvickers
Copy link
Member

@smitpatel Can you confirm that this is too risky for a patch release?

@h0s See the planning process for information on when we patch.

@smitpatel
Copy link
Contributor

Yes, it is too risky for patch and also involves API breaks.

@jeremy-holovacs-sp
Copy link

... so even though 3.1 is in LTS, this is not going to be fixed? Are we being forced to upgrade to 6.0 to get this working?

@ajcvickers
Copy link
Member

@jeremy-holovacs-sp That's correct. The fix is too risky to include in a patch. See release planning for more information.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-query closed-fixed The issue has been fixed and is/will be included in the release indicated by the issue milestone. customer-reported punted-for-5.0 type-bug
Projects
None yet
Development

No branches or pull requests

6 participants