Ale*_*x70 5 linq entity-framework
是否有可能将IQueryable对象转换为IQueryable,其中T是映射实体?(T将是POCO类).
提前致谢.
Jef*_*ado 11
就是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`)
Run Code Online (Sandbox Code Playgroud)
但是在您的情况下,您说您正在使用Dynamic LINQ并进行动态投影.考虑这个完全构成的查询:
var query = dc.SomeTable
.Where("SomeProperty = \"foo\"")
.Select("new (SomeProperty, AnotherProperty)");
Run Code Online (Sandbox Code Playgroud)
它导致查询类型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...
}
Run Code Online (Sandbox Code Playgroud)
如果要将其转换为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,
});
Run Code Online (Sandbox Code Playgroud)
如果你必须有IQueryable<T>,那么你不应该首先使用动态投影.
IQueryable<SomePoco> query =
dc.SomeTable
.Where("SomeProperty = \"foo\"")
.Select(x => new SomePoco
{
SomeProperty = x.SomeProperty,
AnotherProperty = x.AnotherProperty,
});
Run Code Online (Sandbox Code Playgroud)
看看转换如何不适用于LINQ to Entities,那么我认为你必须获得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,
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2348 次 |
| 最近记录: |