Reputation: 339
I have base class, and multiple derived classes, like that:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Parent : Person
{
public int Age { get; set; }
}
public class Child : Person
{
public int Grade { get; set; }
public Parent Father { get; set; }
public Parent Mother { get; set; }
}
Each class has a table in the DB, with an appropirate field.
When I want to obtain data from the DB, and initalize an Person's instance, I need to set value for each property, like that:
Name = reader["Name"].ToString();
Age = int.Parse(reader["Age"].ToString());
Now, I don't want to do that on each derived class, but do that generally in the base class. What is the best way to do that? Thank you.
Upvotes: 0
Views: 145
Reputation: 64933
First of all, the best answer you can find here is: adopt an OR/M like Entity Framework, NHibernate or Dapper (or any other) and focus your efforts in your business instead of wasting your time in infrastructure details!
In the other hand, if you want an approach to solve your issue using your own code, I would say you need to create the concept of data mapper. It would be a class which should define mapping between relational and object-oriented counterparts.
This way, when you try to obtain a derived class, you instantiate base class and derived class data mappers, and you call them to obtain the entire column data:
DerivedClass derivedClassInstance = new DerivedClass();
DerivedClassDataMapper derivedMapper = new DerivedClassDataMapper(derivedClassInstance, dataReader);
derivedMapper.Fetch();
// Now your derivedClassInstance reference will contain an object which
// has both data from base and derived class...
Finally, I would say that both data mappers should inherit from a DataMapper
base class where Fetch
method should be marked as virtual
(or abstract
) in order to let derived data mappers add more mapping code (this way, base mapper will map properties to columns defined in the base class, derived class will override Fetch
to add more mappings and so on...).
Anyway, you shouldn't reinvent the wheel because there're solid object-relational mappers.
Upvotes: 1