Search code examples
c#entity-frameworklinqentity-framework-corelinq-to-entities

Has EF Core introduced a change in behavior that allows direct entity projection in LINQ queries?


I'm working with EF Core 8 and the MySql provider (Pomelo) in my .NET project. I'm encountering a curious situation where the following code snippet runs without needing Dtos and doesn't produce the error "The entity cannot be constructed in a LINQ to Entities query"

What changed in EF Core, or is there something wrong with my code? I remember you needed to use Dtos for this situation or else it will throw an error. Any insights would be appreciated!

public DbSet<Product> Products { get; set; }
var list = DbContext.Products
    .Select(x => new Product()
    {
        ID = x.ID,
        Name = x.Name,
        Qty = x.Qty,
    }).ToList();

I'm using the following EF Core package references:

<PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.10" />
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="8.0.2" />

Solution

  • It was an unintended (and unusual) limitation in Entity Framework 6.

    In EF Core, this limitation has been removed, allowing you to project to a model class without encountering translation errors.