Entity Framework Core 3.0 - Lambda expression used inside Include is not valid

asp.net-core c# entity-framework-core

Question

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 ?

1
1
12/19/2019 11:48:37 PM

Accepted Answer

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.

3
12/20/2019 12:05:52 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow