Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 734
Sami-L Avatar asked Dec 19 '19 23:12

Sami-L


1 Answers

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.

like image 64
James Avatar answered Nov 01 '22 02:11

James