Here below I am using lambda expression in LINQ Includes for 1 level, to fetch a list of customers using three entities, the main one is for all Customers and has only 2 properties Id and bool: IsCompany, the second one has only those that are companies, and the third one has only those that are individuals. The below code was working using .Net Core 2.2, when I updated to 3.0 it stopped working, and most I could find are solutions for multi level such as Include -> ThenIclude that cannot work here. And version 3.0 breaking changes don't mention this case.
public async Task<ActionResult<IEnumerable<CustomersListVM>>> GetCustomers()
{
List<CustomersListVM> customerList = await _context.Customers
.Include(p => p.Company.Name)
.Include(p => p.Individual.Name)
.Select(p => new CustomersListVM
{
Id = p.Id,
CustomerId = p.CustomerId,
Name = p.IsCompany == true ? p.Company.Name : p.Individual.LastName + ' ' + p.Individual.FirstName
}).ToListAsync();
return customerList;
}
Any idea ?
The Include
clause is used to retrieve related objects. The methods should be called with lambdas specifying the linked entities, but without stating .Name
(because this is a property):
.Include(p => p.Company)
.Include(p => p.Individual)
Then in the Select
method, you specify that you only need the Name
of the company/individual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With