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?
``` C#
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
};
}
}
```
i found the following code in ProjectionMember.cs but absolutely no idea 馃 @smitpatel
c#
public override string ToString()
=> _memberChain.Any()
? string.Join(".", _memberChain.Select(mi => mi.Name))
: "EmptyProjectionMember";
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.
It's really tough to create one self contained runnable repro but i'll try my best. Thank you
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.
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 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.
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
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?

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

Hopefully I can get some more context on what's throwing the error.
@AngeloAnolin Did you try removing SingleOrDefault() from your inner projection
@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.
@smitpatel Description in latest posts asserts a regression in 5.0; can you take a look?
@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.
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();