This project has moved and is read-only. For the latest updates, please go here.

Better way to retrieve derived classes?

Mar 1, 2013 at 3:55 PM
Edited Mar 1, 2013 at 3:56 PM
As far as I can tell, I can't retrieved derived classes from a Query<TBaseClass, TKey> because it doesn't support abstract classes for TTable.

I understand the recommendation is to only create table defs for the derived classes.

Is there a better way to achieve that, since right now I pass in an enum that is a discriminator:
// Animal is a abstract base class
// Carnivore and Herbivore are derived from it
public Animal GetAnimalById(int id, AnimalType type) {

    return from q in _db.Query<Animal, int>() // blah

    if (type == AnimalType.Carnivore) {
        return from q in _db.Query<Carnivore, int>() // blah
    } else {
        return from q in _db.Query<Herbivore, int>() // blah
Essentially I have code that just cares about the base properties and not the derived type.
Mar 1, 2013 at 5:08 PM
Hi, you essentially have two options.

You can save it to the different types and retrieve it as you are doing, or you can use the SaveAs method to cast to the base type. In that scenario, you retrieve from the base type and then either inspect it to know the type or cast it to the type you are expecting. Let me know if that answers your questions.
Mar 1, 2013 at 10:00 PM
Edited Mar 1, 2013 at 10:01 PM
Would I need to not use an abstract class then, so I'd add another Table for it? The main issue is that the compiler complains my base class does not have a parameterless constructor.

I'm fine with my approach now, I only have to deal with two derived types, was just wondering if I was missing something.