开发者

IQueryable to IQueryable<T>

is it possibile convert an IQueryab开发者_运维百科le object to IQueryable where T is a mapped entity? (T will be a POCO class).

Thanks in advance.


Just Cast<T>() it. Assuming it is a queryable of the same type. Otherwise you could use the OfType<T>() filtering method to filter out items of a certain type.

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

However in your case, you say that you are using Dynamic LINQ and doing a dynamic projection. Consider this completely made up query:

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

It results in a query of type IQueryable. You cannot cast this to a query of a specific type IQueryable<T> after all, what is T? What the Dynamic LINQ library does is creates a type that derives from DynamicCass. You could cast to IQueryable<DynamicClass> (query.Cast<DynamicClass>()) but you will not have access to the properties so it's moot.

Really the only nice option you have is to use dynamic to access these properties in this case.

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

If you want to convert this to a query of your POCO objects, you'll have to do the conversion as a separate step but using 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,
      });

If you must have an IQueryable<T>, then you should not use dynamic projections in the first place.

IQueryable<SomePoco> query =
    dc.SomeTable
      .Where("SomeProperty = \"foo\"")
      .Select(x => new SomePoco
      {
          SomeProperty = x.SomeProperty,
          AnotherProperty = x.AnotherProperty,
      });

Seeing as how the cast is not working for LINQ to Entities, then I suppose the only option you have to get a strongly type collection of your POCO objects is to break this out into a loop.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜