I have a data access class that loads reference data. Each type of entity will execute it’s own stored procedure and return a result set specific for that entity type. Then I have a method that maps the returned values from the datatable to the entity. All Entity Types have the same public properties of Code and Name how can I make this method generic to handle a type of entity? Something like this is what would presume but the properties are causing an error.
private static T MapDataReaderToEntity<T>(IDataReader reader)
{
var entity = typeof (T);
entity.Code = SqlPersistence.GetString(reader, "Code");
entity.Name = SqlPersistence.GetString(reader, "Name");
return entity;
}
and I would call it with something like this.
_sourceSystem = MapDataReaderToEntity<SourceSystem>(_reader);
If your entities implement an interface with the Code and Name properties defined, you could potentially use something like:
Without the interface, there is no way for the compiler to know about the
CodeorNameproperties. You would need to revert to using Reflection or dynamic code, or some other less-than-ideal mechanism for determining these properties at runtime instead of at compile time.