I am using Entity framework 6 and my query is as below:
var query = await context.Products.Select(p => new Product() { Id = p.Id, Name = p.Name }).ToListAsync();
it doesn't work and it always break;
but if i remove the "Select(p => new Product() { Id = p.Id, Name = p.Name })"
and write like this
await context.Products.ToListAsync(); and it works.
Whats wrong with that?
My Id was Guid
And am doing this with no records in database, I am just checking if my api works.
You must be getting issue The Entity or Complex Type cannot be constructed in a LINQ to Entities Query when executing
var query = await context.Products.Select(p => new Product() { Id = p.Id, Name = p.Name }).ToListAsync();
You should always mention error details when you ask question, so that other users can understand your issue, place all the details of your issue in description when you ask questions
Now back to your question
You cannot (and should not be able to) project onto a mapped entity. You can, however, project onto an annonymous type or onto a DTO
Means you need to create another ViewModel, in your Case Model and ViewModel is same that is "Products"
So, always need to create a New Model(DTO) for fetching data like this
public class ProductDTO
{
public string Name { get; set; }
// Other fields if needed here
}
Your C# code should be
var query = await context.Products.Select(p => new ProductDTO() { Name = p.Name ]}).ToListAsync();
Simply create a data to object Model, to make .ToListAsync work
var getProducts = await context.Products.Select(p => new YourDataModel() { Name = p.Name ]}).ToListAsync();
That's easy, way to resolve error.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly