2011-05-11 55 views
3

是否可能将IQueryable对象转换为IQueryable,其中T是映射实体? (T将是一个POCO课程)。IQueryable to IQueryable <T>

在此先感谢。

+2

而你如何获得非泛型'IQueryable'? – 2011-05-11 13:08:16

回答

8

只是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`) 

不过你的情况,你说你正在使用动态LINQ和做一个动态的投影。考虑这个完全由查询:

var query = dc.SomeTable 
       .Where("SomeProperty = \"foo\"") 
       .Select("new (SomeProperty, AnotherProperty)"); 

它导致IQueryable类型的查询。你不能把这个投射到一个特定类型的查询IQueryable<T>毕竟什么是T? Dynamic LINQ库所做的是创建一个从DynamicCass派生的类型。你可以投到IQueryable<DynamicClass>query.Cast<DynamicClass>()),但你将无法访问属性,所以它是没有意义的。

真的,你拥有的唯一不错的选择是在这种情况下使用dynamic来访问这些属性。

foreach (dynamic x in query) 
{ 
    string someProperty = x.SomeProperty; 
    int anotherProperty = x.AnotherProperty; 
    // etc... 
} 

如果你想将其转换为您的POCO对象的查询,你必须做转换为一个单独的步骤,但使用LINQ to对象。

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, 
    }); 
} 
+0

我得到System.Exception:不能执行类型转换.. Linq转换为实体只支持对原始类型转换.. – Alex70 2011-05-11 13:28:00

+0

所有我需要的是实现一个IQueryable 从动态linq到实体: 步骤1:我已经像这样 - > var query1 = myCtx.Where(.. lambda); 第2步:我必须选择只是一些领域(我不能在这里使用拉姆达),所以: VAR QUERY2 = query1.Select(“myFiled1,myFiled2); 第2步是可以实现的,通过ScottGu的System.Linq.Dynamic.dll 。图书馆 问题就在这里:在步骤2中返回一个IQueryable,而我需要的IQueryable 其中T是我的POCO类 我不能convert..I转换过程中始终得到异常.. – Alex70 2011-05-11 14:19:20

+0

@Alex:这是如果信息在您提问时很有用,那么在这种情况下,由于您投射到动态类型和技术上,您不能投射到特定类型,因此您不知道编译时间类型。然而,你可以强制转换为DynamicClass,因为这是对象派生的类型,除非你使用'dynamic'变量,否则你将无法直接访问这些字段。 – 2011-05-11 21:01:22