30% OFF - 10th Anniversary discount on Entity Framework Extensions until December 15 with code: ZZZANNIVERSARY10
Entity Framework The entity cannot be constructed in a LINQ Exception
Exception: The entity cannot be constructed in a LINQ to Entities query
In Entity Framework, mapped entities represent database tables, and Entity Framework doesn't allow to project on a mapped entity in a LINQ to Entities query. If you project on a mapped entity, then it will partially load an entity, which is not a valid state. EF won't have any clue how to handle when the entity is updated.
using (var context = new CustomerContext()) { var customer = context.Customers.Where(c => c.CustomerID == 1) .Select(c => new Customer() { Name = c.Name }) .FirstOrDefault(); }
StackOverflow Related Questions
- The entity cannot be constructed in a LINQ to Entities query
- "The entity or complex type cannot be constructed in a LINQ to Entities query" in Controler
Solution
Anonymous Type
The most straightforward solution to handle this exception is to project on anonymous type.
using (var context = new CustomerContext()) { var customer = context.Customers.Where(c => c.CustomerID == 1) .Select(c => new { Name = c.Name }) .FirstOrDefault(); }
DTO
You can also project on Data Transfer Objects (DTO)
using (var context = new CustomerContext()) { var customer = context.Customers.Where(c => c.CustomerID == 1) .Select(c => new CustomerDTO() { Name = c.Name }) .FirstOrDefault(); }
The DTO class will look like this.
public class CustomerDTO { public string Name { get; set; } }
Anonymous Type to Strongly Type
Another way of handling this problem is to project into anonymous type first and then map anonymous type to mapped entity or model entity.
using (var context = new CustomerContext()) { var customers = context.Customers.Where(c => c.CustomerID == 1) .Select(c => new { Name = c.Name }) .ToList() .Select(x => new Customer { Name = x.Name }) .ToList(); }
ZZZ Projects