是否可以将IQueryable对象转换为IQueryable,其中T是映射实体? (T将是一个POCO类)。
谢谢提前。
是否可以将IQueryable对象转换为IQueryable,其中T是映射实体? (T将是一个POCO类)。
谢谢提前。
只需使用 Cast<T>()
。假设它是相同类型的可查询对象。否则,您可以使用OfType<T>()
过滤方法来过滤特定类型的项目。
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`)
var query = dc.SomeTable
.Where("SomeProperty = \"foo\"")
.Select("new (SomeProperty, AnotherProperty)");
IQueryable
。你不能将其强制转换为特定类型的查询 IQueryable<T>
,因为 T
是什么呢?动态 LINQ 库创建了一个从 DynamicClass
派生的类型。你可以将其转换为 IQueryable<DynamicClass>
(query.Cast<DynamicClass>()
),但是您将无法访问属性,因此这是无意义的。
实际上,在这种情况下,您唯一的好选择是使用 dynamic
访问这些属性。
foreach (dynamic x in query)
{
string someProperty = x.SomeProperty;
int anotherProperty = x.AnotherProperty;
// etc...
}
如果您想将此转换为POCO对象的查询,您需要将转换作为单独的步骤,但使用LINQ to Objects进行。
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 to Entities不支持cast,那么您唯一的选择就是将其拆分成循环以获得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,
});
}
DynamicClass
,因为这些对象都是从该类型派生的,但是除非使用dynamic
变量,否则无法直接访问字段。 - Jeff Mercado
IQueryable
? - Ladislav Mrnka