Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - query specifying inherited type for navigation property

So I have an entity that has a navigation property which has a type with a class hierarchy. (entity names changed to protect the guilty)

class ParentEntity
{
  virtual ChildEntity TheProperty { get; set; }
  virtual string AnotherProperty { get; set; }
  virtual string AnotherProperty2 { get; set; }
}

class ChildEntity
{
}

class ChildSubEntity : ChildEntity
{
  virtual string InterestingProperty { get; set; }
}

How can I query for ParentClass entities, with one of my query conditions being where TheProperty is of type ChildSubClass and InterestingProperty has a particular value?

I've tried

ObjectContext context = GetContext();
var result = context.ParentEntities.
  Where(e => e.AnotherProperty == AnotherInterestingValue).
  Where(e => e.TheProperty is ChildSubEntity).
  Where(e => ((ChildSubEntity)e.TheProperty).
    InterestingProperty == InterestingValue).
  ToList();

And get the error "Unable to cast the type 'ChildEntity' to type 'ChildSubEntity'. LINQ to Entities only supports casting Entity Data Model primitive types.".

I'm having to settle for flattening the list, and applying this condition after the data has been retrieved from the entity store. Is it possible to write this condition in a form LINQ to Entities will accept?

To be clear, this is a simplification, I'm actually applying a number of conditions programmatically, building a query expression using LinqKit, with some of the conditions being on properties of ParentEntity, some on ParentEntity, and some on other child entities of ParentEntity.

like image 375
SamStephens Avatar asked Aug 25 '11 05:08

SamStephens


1 Answers

You have to use OfType its correctly resolved by LINQ to Entities. Use it against ChildEntity collection and select ParentEntities related to selected ChildEntity objects.

ObjectContext context = GetContext();
var result = context.ChildEntities.OfType<ChildSubEntity>
.Where(e => e.InterestingProperty == InterestingValue)
.SelectMany(e = > e.ParentEntity)
.ToList();
like image 145
Piotr Auguscik Avatar answered Nov 03 '22 01:11

Piotr Auguscik