是否有可能将IQueryable对象转换为IQueryable,其中T是映射的实体?(T将是波科班)。
提前谢谢。
发布于 2011-05-11 13:11:40
只是Cast()它。假设它是相同类型的查询。否则,可以使用OfType()筛选方法筛选出特定类型的项。
IQueryable query = ...;
IQueryable<MyType> x = query.Cast<MyType>(); // assuming the queryable is of `MyType` objects
IQueryable<MyDerivedType> y = query.OfType<MyDerivedType>(); // filter out objects derived from `MyType` (`MyDerivedType`)然而,在您的情况下,您说您正在使用动态LINQ并执行动态投影。考虑一下这完全是虚构的查询:
var query = dc.SomeTable
.Where("SomeProperty = \"foo\"")
.Select("new (SomeProperty, AnotherProperty)");它会产生一个IQueryable类型的查询。您不能将其转换为特定类型的IQueryable<T>查询,毕竟,T是什么?动态LINQ库所做的是创建一个从DynamicCass派生的类型。您可以转换为IQueryable<DynamicClass> (query.Cast<DynamicClass>()),但是您将无法访问这些属性,因此这是没有意义的。
实际上,在这种情况下,使用dynamic访问这些属性是唯一好的选择。
foreach (dynamic x in query)
{
string someProperty = x.SomeProperty;
int anotherProperty = x.AnotherProperty;
// etc...
}如果要将其转换为POCO对象的查询,则必须作为单独的步骤进行转换,但要使用LINQ对象。
IEnumerable<SomePoco> query =
dc.SomeTable
.Where("SomeProperty = \"foo\"")
.Select("new (SomeProperty, AnotherProperty)")
.Cast<DynamicObject>().AsEnumerable().Cast<dynamic>()
.Select(x => new SomePoco
{
SomeProperty = x.SomeProperty,
AnotherProperty = x.AnotherProperty,
});如果您必须有一个IQueryable<T>,那么首先不应该使用动态投影。
IQueryable<SomePoco> query =
dc.SomeTable
.Where("SomeProperty = \"foo\"")
.Select(x => new SomePoco
{
SomeProperty = x.SomeProperty,
AnotherProperty = x.AnotherProperty,
});考虑到LINQ实体的强制转换是如何工作的,那么我认为您必须获得POCO对象的强类型集合的唯一选项是将其分解为一个循环。
var query = dc.SomeTable
.Where("SomeProperty = \"foo\"")
.Select("new (SomeProperty, AnotherProperty)");
var result = new List<SomePoco>();
foreach (dynamic x in query)
{
result.Add(new SomePoco
{
SomeProperty = x.SomeProperty,
AnotherProperty = x.AnotherProperty,
});
}https://stackoverflow.com/questions/5964724
复制相似问题