2

I think I use TPT inheritance. I have an abstract parent class and three subclasses. What I want is a basic find function, but I need to explicitly do includes. My problem is how can I include different properties based on the type.

public List<RandomObject> FindAll(int someProperty)
{
    using (MyContext db = new MyContext())
    {
        var randomObjects = db.RandomObjects.Where(x => x.SomeProperty == someProperty);
    }
}

Each instance of RandomObject has a collection of the abstract Superclass. There are a fixed number of known subclasses (we can call them SubclassA and SubclassB if people need names).

I have been trying various Include statements such as this

randomObjects = randomObjects.Include(x => x.Superclasses.OfType<SubclassA>().SubclassAOnlyProperty);

If there is any clarification needed just let me know, I could definitely fill this post with all sorts of things I have tried.

Alec
  • 1,646
  • 3
  • 19
  • 35
  • `Include` and inheritance don't play nice together. The simple advice is don't use `Include` to get relations of multiple derived types in single query and especially don't use `Include` for this with TPT (until .NET 4.5 is out). – Ladislav Mrnka Nov 29 '11 at 09:40
  • So what are my alternatives in terms of lazy/eager loading? The data I need is a list of this abstract subclass, and this data includes several relationships specific to only certain subclasses. How can I retrieve this TPT data without resorting to `Include`? – Alec Nov 29 '11 at 20:22

1 Answers1

0

Something like this might work:

var result = MyContext.randomObjects
    .Select(r => new
    {
        RandomObj = r,
        SuperclassesOfTypeA = r.Superclasses.OfType<SubClassA>().Select(subA => new {
            obj = subA,
            SubclassAOnlyProperty = subA.SubclassAOnlyProperty
        }),
        AllSuperClasses = r.Superclasses
    })
    .ToList();

I think that would give you an in-memory collection of anonymous objects, where RandomObj would be the main object, SuperclassesOfTypeA would be a collection of anonymous objects representing your Super classes that are of type SubClassA, with SubclassAOnlyProperty eager loaded, and for good measure a collection of all your other superClasses.

Adam Rackis
  • 82,527
  • 56
  • 270
  • 393
  • Since my end goal is to have a RandomObject with a List that is the concatenation of the lists of subclasses, how might I go about ending up with that? Right now I just create a RandomObject from result.RandomObj and then set the List property to a concatenation of the Result.SubclassAList, Result.SubclassBList, etc. It seems pretty messy, but is it the best way? – Alec Nov 29 '11 at 08:23
  • @OpticalDelusion - I'm really not sure. I think you should ask that as a new question. – Adam Rackis Nov 29 '11 at 15:25