IQueryable for IQueryable <T>

Is it possible to convert an IQueryable to IQueryable where T is the displayed object? (T is a POCO class).

Thanks in advance.

+3
source share
1 answer

Just Cast<T>()it. Assuming this is a query of the same type. Otherwise, you can use the filter method OfType<T>()to filter elements 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 dynamic projection. Consider this fully populated request:

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

All Articles