Skip to content
Advertisement

LINQ to SQL, select from an inheritted class

Using LINQ to SQL and Object Relational Designing; Let’s say we have a class Animal with two inherited classes, named Cat and Dog. We can load the “Animal” class and its properties easily:

var animals = from a in dataContext.Animals
              select a;

However, when trying to load Cat or Dog, dataContext has the attribute of neither Cats nor Dogs. How is it possible to load a Cat or a Dog from the table Animal with their own extra properties?

Thanks in advance.

Advertisement

Answer

Use the OfType<T>:

var dogs = from a in dataContext.Animals.OfType<Dog>()
              select a;

and for cats:

var cats = from a in dataContext.Animals.OfType<Cat>()
              select a;

Like shown here

… and a complete example here

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement