I am creating a generic data reader function for get data from database but i am facing a issue. "Unable to cast object of type ‘System.String’ to type ‘MyBooks.Data.Model.Book"
Kindly Help me
public List<T> GetDataMethod<T>(SqlCommand cmd)
{
cmd.Connection = getcon();
SqlDataReader reader = cmd.ExecuteReader();
List<T> records = new List<T>();
while (reader.Read())
{
object[] tempRow = new object[reader.FieldCount];
for (int i = 0; i < reader.FieldCount; i++)
{
tempRow[i] = reader[i];
}
//Error showing > can not convert from object[] to T
records.Add(tempRow);
}
return records;
}
3
Answers
You can use a generic type. You’ll need to return a list of objects then create code to map between the list of objects to the type you need.
tempRow is a DataRow. And T is of type MyBooks.Data.Model.Book.
What you want to do is map the values to the properties of Book.
E.g. if Book has a property of "Title" and you know, that the title is in the DataRow at index 0:
this is what all ORMs do. they need a specific mapper for each type that would be provided by the reflection, annotation, or anything else. Bytheway you could register your own mappers and use them inside your method.
if you have model for Book.
and you need an interface for all your mappers like this :
and the book mapper :
also, you need somewhere to register your mappers to DI :
now you would be able to change your method like this :