Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 594
Brendan Vogt Avatar asked Oct 12 '25 12:10

Brendan Vogt


2 Answers

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;
     }
}
like image 77
Eranga Avatar answered Oct 15 '25 03:10

Eranga


ICollection is used only as the backing property to support LazyLoading, not as the result of a method. Check here ;)

like image 43
tec-goblin Avatar answered Oct 15 '25 02:10

tec-goblin