Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type IEnumerable<T> to IQueryable<T>

Obfuscated Scenario: A person has zero, one or many pets.

Using Linq to Sql, the need is to get an IQueryable list of pets for the given personID. Here's the poorly mangled/butchered/obfuscated portion of the ERD:

alt text

Code:

 public IQueryable<Pet> GetPersonPets(int personID)
    {
        var personPets= from p in Person
        where p.ID == somePersonID
        select p.Pets;

        return personPets; //fail
        // return (IQueryable<Pet>)personPets  //also fail
        // return personPets.AsQueryable<Pet>()  //also fail
    }

Exception Raised:

Cannot implicitly convert type 
'System.Collections.Generic.IEnumerable (System.Data.Linq.EntitySet(Pet))' 
to 'System.Linq.IQueryable(Pet)'. 
An explicit conversion exists (are you missing a cast?) 

Failed Attempts:

Direct casting didn't work: (IQueryable<MyType>)

Calling collection method AsQueryable didn't work: .AsQueryable<MyType>()

Question:

How can you cast the results of the LinqToSql query properly to IQueryable?

like image 235
p.campbell Avatar asked Jul 04 '09 01:07

p.campbell


3 Answers

This works for me (with different tables of course, but same relationship):

IQueryable<Pet> personPets = (
   from p in db.Person
   where p.ID == somePersonID
   select p
).Single().Pets.AsQueryable();

Although I'd probably write it in some variation of this way:

var personPets = 
    db.Person.Single(t => t.Id == somePersonId).Pets.AsQueryable();    
like image 180
Blorgbeard Avatar answered Oct 10 '22 03:10

Blorgbeard


List<Pet> personPets = 
   (from p in Persons
   where p.ID == somePersonID
   select p.Pets).ToList();

Try something like this.

like image 20
Andrew Siemer Avatar answered Oct 10 '22 05:10

Andrew Siemer


Look at your query:

    var personPets= from p in Person
    where p.ID == somePersonID
    select p.Pets;

What is happening is that you are returning an IEnumerable (of one element) of IEntitySet<Pet> types (the type: IEnumerable<IEntitySet<Pet>>).

You should get an IEnumerable<Pet> and it will be converted to IQueryable<Pet> by the AsQueryable method:

public IQueryable<Pet> GetPersonPets(int personID)
{
    var person = Person.Single(p=> p.ID == personID);

    return person.Pets.AsQueryable();
}
like image 2
Christian C. Salvadó Avatar answered Oct 10 '22 03:10

Christian C. Salvadó