首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >IQueryable到IQueryable<T>

IQueryable到IQueryable<T>
EN

Stack Overflow用户
提问于 2011-05-11 13:05:12
回答 1查看 4.6K关注 0票数 6

是否有可能将IQueryable对象转换为IQueryable,其中T是映射的实体?(T将是波科班)。

提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2011-05-11 13:11:40

只是Cast()它。假设它是相同类型的查询。否则,可以使用OfType()筛选方法筛选出特定类型的项。

代码语言:javascript
复制
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并执行动态投影。考虑一下这完全是虚构的查询:

代码语言:javascript
复制
var query = dc.SomeTable
              .Where("SomeProperty = \"foo\"")
              .Select("new (SomeProperty, AnotherProperty)");

它会产生一个IQueryable类型的查询。您不能将其转换为特定类型的IQueryable<T>查询,毕竟,T是什么?动态LINQ库所做的是创建一个从DynamicCass派生的类型。您可以转换为IQueryable<DynamicClass> (query.Cast<DynamicClass>()),但是您将无法访问这些属性,因此这是没有意义的。

实际上,在这种情况下,使用dynamic访问这些属性是唯一好的选择。

代码语言:javascript
复制
foreach (dynamic x in query)
{
    string someProperty = x.SomeProperty;
    int anotherProperty = x.AnotherProperty;
    // etc...
}

如果要将其转换为POCO对象的查询,则必须作为单独的步骤进行转换,但要使用LINQ对象。

代码语言:javascript
复制
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>,那么首先不应该使用动态投影。

代码语言:javascript
复制
IQueryable<SomePoco> query =
    dc.SomeTable
      .Where("SomeProperty = \"foo\"")
      .Select(x => new SomePoco
      {
          SomeProperty = x.SomeProperty,
          AnotherProperty = x.AnotherProperty,
      });

考虑到LINQ实体的强制转换是如何工作的,那么我认为您必须获得POCO对象的强类型集合的唯一选项是将其分解为一个循环。

代码语言:javascript
复制
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,
    });
}
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5964724

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档