Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting to a derived type in a LINQ to Entities query with Table Per Hierarchy inheritance

I have a LINQ to entities model with Table Per Hierarchy inheritance. I have a query over the base type, and I want to do specific type-dependent logic. For example:

IQueryable<BaseType> base = ...

// this works fine
var result = base.Select(b => b is DerivedType1 ? 1 : 2).ToList();

// this doesn't compile to SQL
var result2 = base.Select(b => b is DerivedType1 ? ((DerivedType1)b).DerivedProperty : null).ToList();

Is there any way to do something like this without processing IQueryables of each derived type separately:

// I'd rather not do this:
var resultA = base.OfType<DerivedType1>().Select(d => d.DerivedProperty);
var resultB = base.OfType<DerivedType2>().Select(d => default(int?));
var result = resultA.Concat(resultB).ToList();
like image 889
ChaseMedallion Avatar asked Aug 28 '12 19:08

ChaseMedallion


3 Answers

Direct casting to an entity type like (DerivedType1)b isn't supported with LINQ-to-Entities but the as operator (b as DerivedType1) is, hence you could try:

var result2 = base
    .Select(b => b is DerivedType1
        ? (b as DerivedType1).DerivedProperty
        : null)
    .ToList();
like image 162
Slauma Avatar answered Nov 18 '22 02:11

Slauma


OfType<DerivedType1>() 

will return an IEnumerable, if possible, try to change to base-type to IEnumerable instead of IQueryable, you might en up in some SQL restrictions when using IQueryable.

That is of course if you are not actually quering a database?

like image 1
Andreas Johansson Avatar answered Nov 18 '22 03:11

Andreas Johansson


You can use EntityFramework.Extended to improve the performance of the query instead of doing 2 round trips to DB.

var resultA = base.OfType<DerivedType1>().Select(d => d.DerivedProperty).Future();
var resultB = base.OfType<DerivedType2>().Select(d => default(int?)).Future();
var result = resultA.Concat(resultB).ToList();

In this case only one round trip to bd is executed. This framework is very useful for many other things int EF

like image 1
Miguel Avatar answered Nov 18 '22 03:11

Miguel