Say I have a database table called Animals which I drag on to my Linq-2-SQL DBML file.
This creates me a class called Animal.
I then create a class to extend it, like so:
public partial class Animal{
//my extra code here
}
But what I also want to do is have a class like this:
public class Zebra : Animal{
//even more extra code here
}
The trouble is I get an InvalidCastException from my repository, when I do this:
Animal a = dataContext.Animals.Where(c=>c.id.Equals(id)).SingleOrDefault();
return (Zebra)a;
I've stripped back my classes to the point where they're completely empty in an attempt to work why it doesn't work. To no avail.
This casting process did used to work in the non-LINQ-2-SQL project that I'm switching to MVC/LINQ.
Done lots of Googling but completely stumped on this one...
Assuming it can't be done, what the best alternative approach? Interfaces?
Jake
It doesn't work because while a Zebra is an Animal, not all Animals are Zebras. When you get the class it doesn't know anything about the extra methods and properties that belong to class Zebra. If you could cast it as Zebra, it would be missing these.
What you probably should do is make a constructor on Zebra that takes an Animal and produces a Zebra object from that Animal (if possible).
return dataContext.Animals
.Where( c => c.id == id )
.Select( a => new Zebra(a) )
.SingleOrDefault();
Alternatively, you can look at using a column discriminator and baking the subclassing into your data context using inheritance mapping.