efcore icon indicating copy to clipboard operation
efcore copied to clipboard

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

Open suadev opened this issue 6 years ago • 19 comments

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
                };
            }
        }

suadev avatar Mar 13 '20 21:03 suadev

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";

suadev avatar Mar 13 '20 21:03 suadev

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.

smitpatel avatar Mar 15 '20 19:03 smitpatel

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

suadev avatar Mar 15 '20 19:03 suadev

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.

ajcvickers avatar Mar 23 '20 16:03 ajcvickers

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();

arilishu avatar Oct 05 '20 15:10 arilishu

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

ajcvickers avatar Oct 05 '20 18:10 ajcvickers

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

marcin-dardzinski avatar Oct 23 '20 09:10 marcin-dardzinski

I am also encountering this error at the moment.

I did not encounter this issue when I was using .NET Core 3.1 with the applicable EntityFrameworkCore 3.1.8 and EntityFrameworkCore.SqlServer 3.1.8 as well.

A little more context. What makes the error weird is that this happens when I add a couple more LINQ statements to my query. Stripping off some additional LINQ queries eliminates the bug.

What makes this harder to debug is that when I re-position a portion of my query, the error does not show up.

On the VS debug output pane, I have the following logs:

Exception thrown: 'System.Collections.Generic.KeyNotFoundException' in System.Private.CoreLib.dll
An exception of type 'System.Collections.Generic.KeyNotFoundException' occurred in System.Private.CoreLib.dll but was not handled in user code
The given key 'EmptyProjectionMember' was not present in the dictionary.

I can clearly reproduce this thing on my current setup. I will try to come back here with some ways to reproduce it. The randomness of repositioning portions of my queries is what seems to be triggering it.

Below is a sample screenshot of the error happening when I simply positions my query. Notice the last piece of query for the Category? image

Now, if I simply move that Category query before the ContractAssignment query, the code runs fine. image

Hopefully I can get some more context on what's throwing the error.

AngeloAnolin avatar Nov 18 '20 07:11 AngeloAnolin

@AngeloAnolin Did you try removing SingleOrDefault() from your inner projection

Vikas4790 avatar Nov 18 '20 09:11 Vikas4790

@Vikas4790 Removing the SingleOrDefault on the Category query projection would throw an error as the Category object I am projecting is a DTO (which would expect a single object to be cast).

Replacing SingleOrDefault with FirstOrDefault still throws the error.

What has really stumped me is that by simply moving that Category inner query (as per screenshots), the error goes away.

I am playing around with the queries to determine further what is causing the issue.

AngeloAnolin avatar Nov 18 '20 14:11 AngeloAnolin

@smitpatel Description in latest posts asserts a regression in 5.0; can you take a look?

ajcvickers avatar Nov 18 '20 15:11 ajcvickers

@ajcvickers - The original issue was filed much before 5.0 so highly doubt it is regression. New reports can be duplicate of https://github.com/dotnet/efcore/issues/23266 which was regression and had same error message as this one.

smitpatel avatar Nov 18 '20 16:11 smitpatel

Same problem here (KeyNotFoundException). I got this problem after I added the lines:


                .Include(group => group.GroupCoachStudents)
                    .ThenInclude(gcs => gcs.CoachStudentUser.Student)
                .Include(group => group.Sessions)
                    .ThenInclude(session => session.StudentSessions)

in here:

var groups = await repo
    .GetAll()
    .Where(group => group.CoachId == UserId && (groupId == null || group.Id == groupId))
    .Include(group => group.Prices)
    .Include(group => group.Payments)
        .ThenInclude(payment => payment.StartingSession)
    .Include(group => group.GroupCoachStudents)
        .ThenInclude(gcs => gcs.CoachStudentUser.Student)
    .Include(group => group.Sessions)
        .ThenInclude(session => session.StudentSessions)
    .Select(group => new PrelimOwnGroupDto()
    {
        Group = group,
        Students = group.GroupCoachStudents.Select(gcs => new PrelimStudentDto()
        {
            Student = gcs.CoachStudentUser.Student,

            DueSession = group.Sessions
                .Where(session => session.StudentSessions.Any(studentSession => studentSession.StudentId == gcs.CoachStudentUser.StudentId))
                .OrderByDescending(x => x.Date)
                .First()
        }),
        NoNewRequests = group.GroupCoachStudents.Where(x => !x.IsConfirmed).Count(),
        NextSessions = group.Sessions.Where(x => x.Date > now).OrderBy(x => x.Date)
    })
    .ToListAsync();

danielcojocaru avatar Nov 28 '20 23:11 danielcojocaru

This issue contains only 1 runnable repro code provided by @marcin-dardzinski The code is working in EF Core 6.0-preview5. (Associated PR adds regression test for it). For other people who commented on this issue or stumble upon this issue in future, This error comes as a bug from internal implementation. The error on it's own doesn't tell anything about the cause. We will need a runnable repro code to reproduce such errors. So if you are still facing issue after EF Core 6.0-preview5 or higher version, please file a new issue with a runnable repro code.

smitpatel avatar Apr 22 '21 23:04 smitpatel

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();

alexdresko avatar May 15 '23 13:05 alexdresko

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

roji avatar May 16 '23 07:05 roji

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

Webreaper avatar May 14 '24 05:05 Webreaper

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! šŸ¤”

Khungersumit avatar Aug 10 '24 02:08 Khungersumit

I am having the same problem on net 8

nhuthan avatar Aug 16 '24 08:08 nhuthan