问题描述
模糊方案:一个人有零个,一个或多个宠物。
使用Linq到Sql, code> IQueryable 给定personID的宠物列表。
这里是ERD的糟糕的/被屠杀/混淆的部分:
代码:
public IQueryable< Pet> GetPersonPets(int personID)
{
var personPets = from p in Person
其中p.ID == somePersonID
select p.Pets;
return personPets; // fail
// return(IQueryable< Pet>)personPets //也失败
// return personPets.AsQueryable< Pet>()//也失败
}
引发异常:
不能隐式转换类型
'System.Collections.Generic.IEnumerable(System.Data.Linq.EntitySet(Pet))''
到'System.Linq.IQueryable(Pet)' 。
存在显式转换(是否缺少转换?)
尝试失败:
直接转换无效:
(IQueryable< MyType>)
$ b b调用集合方法
AsQueryable
无效:.AsQueryable< MyType>()
问题:
如何将LinqToSql查询的结果正确转换为
IQueryable
?解决方案关系):
IQueryable< Pet> personPets =(
from p in db.Person
其中p.ID == somePersonID
select p
).Single()。Pets.AsQueryable();
虽然我可能会用这种方式写一些变化:
var personPets =
db.Person.Single(t => t.Id == somePersonId).Pets.AsQueryable
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: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
?解决方案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();
这篇关于无法隐式转换类型IEnumerable< T>到IQueryable< T>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!