Generic SqlDataReader for object mapping

I am trying to create a generic cardper that converts the results of SqlDataReader into a class object.

Here is the basic structure for my code:

public interface IObjectCore { //contains properties for each of my objects } public class ObjectMapper<T> where T : IObjectCore, new() { public List<T> MapReaderToObjectList(SqlDataReader reader) { var resultList = new List<T>(); while (reader.Read()) { var item = new T(); Type t = item.GetType(); foreach (PropertyInfo property in t.GetProperties()) { Type type = property.PropertyType; string readerValue = string.Empty; if (reader[property.Name] != DBNull.Value) { readerValue = reader[property.Name].ToString(); } if (!string.IsNullOrEmpty(readerValue)) { property.SetValue(property, readerValue.To(type), null); } } } return resultList; } } public static class TypeCaster { public static object To(this string value, Type t) { return Convert.ChangeType(value, t); } } 

For the most part, this works, but as soon as it tries to set the property value, I get the following error:

Object does not match target type

in the line where I have property.SetValue .

I tried everything and I don’t see what I can do wrong.

+4
source share
2 answers

You are trying to set the value of the property you are looping, I think you intend to set the value of the newly created item that you have, because it will match the type that you pass to it based on item.GetType ()

 var item = new T(); //other code property.SetValue(item , readerValue.To(type), null); 

instead

 property.SetValue(property, readerValue.To(type), null); 

Also for comment make sure you have:

 resultList.Add(item); 
+4
source

This part seems to be wrong:

property.SetValue(property, readerValue.To(type), null);

Are you sure you want to apply SetValue by passing property ? I suppose you should pass an object of type T, which is item .

Then it will be:

property.SetValue(item, readerValue.To(type), null);

+1
source

Source: https://habr.com/ru/post/1381363/


All Articles