.ToList() in MVC api Core 2

2.6k views Asked by At

maybe this asked before, but don't get a good answer. I create a mvc API in mvc Core 2 then implement my interface, in Get all Method when I want get list of All Customers get this error, in below show my code:

using System;
using System.Collections.Generic;
using Dates.Api.Contacts;
using Dates.Model;
using System.Linq;
using Microsoft.EntityFrameworkCore.Design;

public IEnumerable<Customer> GetAll()
    {
      return  _db.Customer.ToList();
    }

'Customer' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'Customer' could be found (are you missing a using directive or an assembly reference?)

UPDATE AFTER COMMENT: Customer is as class for code first in another project in the same solution,

UPDATE TWO: the first think was my mistake for use Customer without DbSet :) but when use it get this error:

The type 'IQueryable<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Core, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
I open myproject.API.csproj and these are my dependency

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0" />
<PackageReference Include="System.Core" Version="3.5.21022.801" />

1

There are 1 answers

0
ironstone13 On BEST ANSWER

If your Customer is a subclass of DBSet<T> then I believe in EF6 there is only an async to list method, see here

Generally, blocking a thread in a synchronous call to IO is not a good practice, so it is best to use async/await

So you could do

public Task<IEnumerable<Customer>> GetAll()
{
    return await _db.Customer.ToListAsync();
}

But that would, of course change your method signature