4
I have a method in which one of the parameters is an object of an abstract class - Objectmapper - whose purpose is to convert an object of one class into another of another class. Below, the method signature informs that the objectMapper will receive as input a Dbdatareader and return a generic T object
public T Select<T>(string query, ObjectMapper<T, DbDataReader> objectMapper)
{
var reader = dbConnector.CreateCommand(query).ExecuteReader();
try
{
return objectMapper.from(reader);
}
catch (Exception e)
{
throw e;
}
finally
{
reader.Close();
}
}
As I come from the Java background, for cases that I don’t need to create a class, just use an anonymous class. However, it seems that C# does not provide this functionality, so I could invoke the method as follows
Select<Pessoa>("SELECT * FROM PESSOA", new ObjectMapper<Pessoa, DbDataReader>() {
public override Pessoa from(DbDataReader reader) {
Pessoa p = new Pessoa();
/** Populo o objeto p a partir do objeto DbDataReader **/
return p;
}
});
What should you do to adapt - or even create a new method - so that I can pass an "anonymous class" to the Select method ?
UPDATE
Follows the class Objectmapper
public abstract class ObjectMapper<T, Source>
{
public abstract T from(Source source);
public static bool hasColumnName(DbDataReader reader, string columnName)
{
for (int i = 0; i < reader.FieldCount; i++)
{
if (reader.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
{
return true;
}
}
return false;
}
/** Outros métodos utilitários **/
}
This class would be an adaptation of the Rowmapper class used by the Spring framework
http://www.mkyong.com/spring/spring-jdbctemplate-querying-examples/
It actually provides, yes, but I wanted to understand where this comes from
ObjectMapper
. It’s from some ORM?– Leonel Sanches da Silva
@Gypsy Morrison Mendez No gypsy. I will post the class
– Arthur Ronald
The class Objectmapper has some other method Abstract? The method
Select
needs the class Objectmapper or only to access the methodfrom
?– ramaral
@ramaral Abstract only from method. Select method only needs to access from method. Utility methods are usually accessed by Objectmapper class instances
– Arthur Ronald
The method
from
access some method/property of Objectmapper?– ramaral
@ramaral Classes that inherit Objectmapper - and consequently implement the from method - can access static methods of the Objectmapper class, such as hasColumnName
– Arthur Ronald