This is a follow up to: Best way to save type of class in database?, well almost the same question but in a more general manner.
I often come across a situation where a base class/interface object has to be saved to database, and I need to read data back, instantiate as actual concrete objects and return a list.
A simple demo would explain it better.
interface IFeline
{
Name;
}
class Leopard
{
Name;
}
class Cheetah
{
Name;
}
I would be saving to database like this:
IFeline felix = new Cheetah();
felix.Save(); //saved to db
Now I need to get a list of felines from db.
public IEnumerable<IFeline> GetThemAll()
{
//connection
//query command
//reader
while(reader.Read())
yield return new ... { } //how do I get the actual felines here?
}
I hope the question is clear. I do not have separate tables for every concrete class They are all generic, and one table is sufficient to hold them.
I want to get the concrete instance from table. I know some sort of type information has to be saved along with the data. I can try a few approaches like saving type as string in the db table, or even enum to denote the type in database. Now my question is, is there a common approach/industry standard to tackle this problem?