Skip to content

The given key 'EmptyProjectionMember' was not present in the dictionary #20277

Closed

Description

@suadev

In the following method, i got exception which i mentioned the title. But if i uncomment the following line it works.

// PreferenceIds = new List()

In which cases this type of exception may occur, any clue?

       public static Expression<Func<ReservationGuest, GuestDto>> GuestSelector
        {
            get
            {
                return g => new GuestDto
                {
                    Id = g.Id,
                    ProfileId = g.ProfileId,
                    VipLevelId = g.ProfileId.HasValue ? g.Profile.VipLevelId : g.ProfileId,
                    VipLevelCode = g.ProfileId.HasValue
                        ? g.Profile.VipLevel.Code
                        : (g.VipLevelId.HasValue ? g.VipLevel.Code : null),
                    LanguageId = g.ProfileId.HasValue ? g.Profile.Language.Id : g.LanguageId,
                    LanguageName = g.ProfileId.HasValue
                        ? g.Profile.Language.Name
                        : (g.Language != null ? g.Language.Name : string.Empty),
                    BirthDate = g.ProfileId.HasValue ? g.Profile.BirthDate : null,
                    IsOwner = g.IsOwner,


                    // PreferenceIds = new List<Guid>(),   // works fine
                    PreferenceIds = g.ProfileId != null && g.Profile != null  // exception
                        ? g.Profile.Preferences.Select(p => p.PreferenceId).ToList()
                        : g.Preferences.Select(p => p.PreferenceId).ToList(),


                    FirstName = g.ProfileId.HasValue ? g.Profile.FirstName : g.FirstName,
                    LastName = g.ProfileId.HasValue ? g.Profile.LastName : g.LastName,
                    MiddleName = g.ProfileId.HasValue ? g.Profile.MiddleName : g.MiddleName,
                    PhoneCode = g.ProfileId.HasValue
                        ? g.Profile.Communications
                            .Where(c => c.Type == CommunicationType.Phone && c.IsPreferred)
                            .Select(y => y.PhoneCode).FirstOrDefault()
                        : g.PhoneCode,
                    PhoneNumber = g.ProfileId.HasValue
                        ? g.Profile.Communications
                            .Where(c => c.Type == CommunicationType.Phone && c.IsPreferred)
                            .Select(c => c.Value).FirstOrDefault()
                        : g.PhoneNumber,
                    Email = g.ProfileId.HasValue
                        ? g.Profile.Communications
                            .Where(c => c.Type == CommunicationType.Email && c.IsPreferred)
                            .Select(c => c.Value).FirstOrDefault()
                        : g.Email
                };
            }
        }

Activity

  1. suadev commented on Mar 13, 2020

    @suadev
    Author

    i found the following code in ProjectionMember.cs but absolutely no idea 🤒 @smitpatel

            public override string ToString()
                => _memberChain.Any()
                    ? string.Join(".", _memberChain.Select(mi => mi.Name))
                    : "EmptyProjectionMember";
  2. smitpatel commented on Mar 15, 2020

    @smitpatel
    Contributor

    The exception message is coming from internal implementation hence the message does not indicate what is wrong directly. Generally this error comes when looking for particular mapped projection which is not present. It is caused either by query is running in client and not appropriately handled to throw client eval exception or corrupt state during translation which is EF Core bug. Please provide runnable repro code which throws above exception so we can investigate root cause. Based on LINQ posted above, I am not able to see what would cause the error like this. Once we have identified root cause, we may be able to provide a work-around.

  3. suadev commented on Mar 15, 2020

    @suadev
    Author

    It's really tough to create one self contained runnable repro but i'll try my best. Thank you

  4. ajcvickers commented on Mar 23, 2020

    @ajcvickers
    Contributor

    EF Team Triage: Closing this issue as the requested additional details have not been provided and we have been unable to reproduce it.

    BTW this is a canned response and may have info or details that do not directly apply to this particular issue. While we'd like to spend the time to uniquely address every incoming issue, we get a lot traffic on the EF projects and that is not practical. To ensure we maximize the time we have to work on fixing bugs, implementing new features, etc. we use canned responses for common triage decisions.

  5. arilishu commented on Oct 5, 2020

    @arilishu

    hi @ALL..
    Let me add my case here please.

    public class Leads
    {
    public Leads()
    {
    DateCreated = DateTime.Now;
    Hash = Helpers.CreateGuid(16);
    CP = "";
    States = new List();
    Vehicles = new List();
    Actions = new List();
    }
    [Key]
    public int Id { get; set; }
    [Required]
    [MaxLength(100)]
    public string Name { get; set; }

        [Required]
        [MaxLength(100)]
        public string Email { get; set; }
        [Required]
        [MaxLength(100)]
        public string Phone { get; set; }
        [Required]
        public DateTime DateCreated { get; set; }
        [Required]
        [Range(18,100)]
        public int Age { get; set; }
        [Required]
        [StringLength(24)]
        public string Hash { get; set; }
        [StringLength(10)]
        public string EnvialoSimpleID { get; set; }
        [StringLength(20)]
        public string DNI { get; set; }
        [StringLength(100)]
        public string Address { get; set; }
        [StringLength(10)]
        public string CP { get; set; }
        public IList<LeadState> States { get; set; }
        public IList<Vehicles> Vehicles { get; set; }
        public IList<Customers> Customers { get; set; }
        public IList<Actions> Actions { get; set; }
    }
    

    public class Vehicles
    {

        public Vehicles()
        {
            Active = true;
            CreatedDate = DateTime.Now;
            Hash = Helpers.CreateGuid();
        }
        [Key]
        public int Id { get; set; }
        [Required]
        public string Hash { get; set; }
    
        [Required]
        public Leads Lead { get; set; }
        [MaxLength(100)]
        public string Brand { get; set; }
        [MaxLength(100)]
        public string Model { get; set; }
        public float Code { get; set; }
        [MaxLength(10)]
        public string Domain { get; set; }
        public int Year { get; set; }
        public bool isNew { get; set; }
        [MaxLength(100)]
        public string Chassis { get; set; }
        [MaxLength(100)]
        public string Engine{ get; set; }
        [Required]
        public bool Active { get; set; }
        public bool isCar { get; set; }
        [Required]
        public DateTime CreatedDate { get; set; }
        public IList<QuotationsGroups> QuotationsGroups { get; set; }
        public IList<Policies> Policies { get; set; }
    
    }
    

    public class Actions
    {
    public Actions()
    {
    DateCreated = DateTime.Now;
    User = User;
    }
    [Key]
    public int Id { get; set; }
    [Required]
    public DateTime DateCreated { get; set; }
    [Required]
    public string Message { get; set; }
    [Required]
    public Leads Lead { get; set; }
    [Required]
    public Users User { get; set; }

    }
    

    public class Policies
    {
    public Policies()
    {
    CreatedDate = DateTime.Now;
    Active = true;
    Comment = "";
    }
    [Key]
    public int Id{ get; set; }
    ///


    /// De qué vehiculo es la póliza?
    ///

    public Vehicles Vehicle{ get; set; }
    ///
    /// Ruta de la póliza en archivos
    ///

    [MaxLength(500)]
    public string Policy { get; set; }
    public bool Active { get; set; }
    ///
    /// Fecha desde que tiene cobertura el usuario
    ///

    public DateTime? FromDate { get; set; }
    ///
    /// Fecha que expira la póliza
    ///

    public DateTime? ExpirationDate { get; set; }
    public DateTime CreatedDate { get; set; }
    ///
    /// Podemos llegar a agregar un comentario a la póliza
    ///

    [MaxLength(500)]
    public string Comment { get; set; }
    ///
    /// Cobertura que tiene el usuario
    ///

    public PoliciesCoverages? Coverage { get; set; }
    ///
    /// Franquicia del auto en caso que sea Todo Riesgo
    ///

    public int Franchise { get; set; }
    ///
    /// Es la conversión de la póliza de su original a txt
    ///

    public string? PolicyTXT { get; set; }
    //Si es lead, no tiene categoría
    public PoliciesCategories? Category { get; set; }
    ///
    /// Si es cliente nuestro tiene quote, pero si es lead no.
    ///

    public Quotes? Quote { get; set; }
    ///
    /// Precio que paga cuando tomamos la póliza
    ///

    [Column(TypeName = "money")]
    public decimal Price { get; set; }
    ///
    /// Si es cliente nuestro tiene quote, pero si es lead no.
    ///

    [Column(TypeName = "money")]
    public decimal lastQuotePrice { get; set; }
    ///
    /// Si es cliente nuestro tiene sumaAsegurada, pero si es lead no.
    ///

    [Column(TypeName = "money")]
    public decimal lastQuoteSumAssured { get; set; }

        public Insurers Insurer { get; set; }
    }
    

    public class LeadsIngresadosVM
    {
    public LeadsIngresadosVM()
    {
    Lead = new Leads();
    Action = new Actions();
    Vehicle = new Vehicles();
    Policy = new Policies();
    }
    public Leads Lead{ get; set; }
    public Actions Action { get; set; }
    public Vehicles Vehicle { get; set; }
    public Policies Policy { get; set; }

    }
    

    And the problem is:
    var leads = db.Leads.Where(x => x.States.Count == 1).OrderByDescending(x => x.Id)
    .Include(x => x.Actions).Include(x => x.Vehicles).ThenInclude(s => s.Policies)
    .Select(x => new LeadsIngresadosVM
    {
    Lead = x,
    Action = x.Actions.OrderByDescending(s => s.Id).FirstOrDefault(),
    Vehicle = x.Vehicles.FirstOrDefault()
    })
    .ToList();

  6. ajcvickers commented on Oct 5, 2020

    @ajcvickers
    Contributor

    @arilishu The code posted is missing too much for me to be able to compile it without guessing many things. Please attach a small, runnable project or post a small, runnable code listing that reproduces what you are seeing so that we can investigate.

  7. marcin-dardzinski commented on Oct 23, 2020

    @marcin-dardzinski

    I've noticed the same exception when I refer to the same owned collection twice within one projection and the owned entity itself has an owned type. If I remove the nested owned type from projection or if I refer to the child list only once it is fine. It is also fine if I replace FirstOrDefault with ToList.

    Here is the repro project: https://github.com/marcin-dardzinski/EFCoreProjectionRepro

  8. added this to the 6.0.0 milestone on Oct 26, 2020
  9. 10 remaining items

  10. added a commit that references this issue on Apr 23, 2021
    0334c7a
  11. ghost closed this as completedin #24737on Apr 23, 2021
  12. ghost added a commit that references this issue on Apr 23, 2021
    682ccb2
  13. modified the milestones: 6.0.0, on Apr 26, 2021
  14. modified the milestones: , 6.0.0 on Nov 8, 2021
  15. alexdresko commented on May 15, 2023

    @alexdresko

    Here's the simplest possible repo, using the starting point: Getting Started - EF Core | Microsoft Learn

    The following query throws the exception. Ignore the fact that this is a silly way to use EF. I'm just trying to narrow the problem down to its smallest repro, and this is what I came up with. It's the 2nd Select that causes the exception to be thrown.

    var blogs = await _bloggingContext.Blogs
        .GroupBy(p => p.BlogId)
        .Select(p => p.First())
        .Select(p => new { S = p.BlogId })
        .ToListAsync();
  16. roji commented on May 16, 2023

    @roji
    Member

    @alexdresko this issue was closed two years ago; if you're still seeing this error, can you please open a new issue?

  17. Webreaper commented on May 14, 2024

    @Webreaper

    Did anyone raise a new issue for this error? I can't find one, but it's still happening in .Net 8.

  18. Khungersumit commented on Aug 10, 2024

    @Khungersumit

    Okay, so here is the discussion about this issue. I am having the same issue.

    query = groupBy(c=>some el)
    Select(g => g.OrderByDescending(m => m.CreatedAt).FirstOrDefault())

    // Culprit
    query= query.OrderByDescending(c => c.CreatedAt);

    This additional sorting operation seems to cause problems. Without this final sort, everything works as expected. I've spent hours trying to figure it out and even tried writing a raw SQL query, but that didn’t solve the problem either. I'm stumped! 🤔

  19. nhuthan commented on Aug 16, 2024

    @nhuthan

    I am having the same problem on net 8

  20. 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

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions