CodexBloom - Programming Q&A Platform

How to implement guide with linq select causing linq to sql conversion failure in ef core 6

👀 Views: 29 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
linq ef-core sql-server C#

I'm experiencing a question where a LINQ query using `Select` is throwing an `InvalidOperationException` when I try to execute it. The specific behavior message is: "The LINQ expression 'DbSet<YourEntity>().Select(...' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation." This happens when I want to project into a custom DTO that includes properties from a navigational property. My setup involves EF Core 6 and I'm querying against a SQL Server database. Here's the relevant part of my code: ```csharp public class YourEntity { public int Id { get; set; } public string Name { get; set; } public virtual RelatedEntity Related { get; set; } } public class RelatedEntity { public int Id { get; set; } public string Description { get; set; } } public class YourDto { public int EntityId { get; set; } public string EntityName { get; set; } public string RelatedDescription { get; set; } } var result = await context.YourEntities .Select(e => new YourDto { EntityId = e.Id, EntityName = e.Name, RelatedDescription = e.Related.Description // This line causes the scenario }) .ToListAsync(); ``` I've confirmed that `Related` is fully populated in the database, so I'm not sure why the projection fails. I've tried using `Include` to load the related data eagerly, but the behavior continues. If I remove the `RelatedDescription` mapping, the query works fine, but I really need this property in my DTO. What can I do to fix this scenario? Is there a way to ensure the navigational property is correctly translated into SQL by EF Core?