Search code examples
asp.net-mvc-3entity-frameworkentity-framework-4entity-framework-4.1

Cannot convert type System.Data.Entity.DbSet to System.Collections.Generic.ICollection


I am using Entity Framework 4.1 code first in an MVC 3 app.

I have the following repository:

public class BankRepository : IBankRepository
{
     HefContext db = new HefContext();

     public ICollection<Bank> GetAll()
     {
          return db.Banks;
     }
}

I get an error when returning db.Banks. I'm not sure what it means, can someone please help clarify and how to change it so that the error goes away? The error is:

Cannot implicitly convert type 'System.Data.Entity.DbSet<MyProject.Core.DomainObjects.Bank>' to 'System.Collections.Generic.ICollection<MyProject.Core.DomainObjects.Bank>'. An explicit conversion exists (are you missing a cast?)

What is returned by db.Banks? An IEnumerable?


Solution

  • db.Banks is of type DbSet. This class does not implement ICollection interface. Change the return type of the method to IQueryable<Bank> or IEnumerable<Bank>.

    public class BankRepository : IBankRepository
    {
         HefContext db = new HefContext();
    
         public IQueryable<Bank> GetAll()
         {
              return db.Banks;
         }
    }