Brendan Vogt
Brendan Vogt

Reputation: 26048

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?

Upvotes: 4

Views: 14787

Answers (2)

Eranga
Eranga

Reputation: 32447

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;
     }
}

Upvotes: 4

tec-goblin
tec-goblin

Reputation: 316

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

Upvotes: 3

Related Questions