C# - IDataReader to Object mapping using generics

后端 未结 10 722
情歌与酒
情歌与酒 2020-12-16 19:07

How can I map a DataReader object into a class object by using generics?

For example I need to do the following:

public class Mapper
    {
          


        
相关标签:
10条回答
  • 2020-12-16 19:35

    I don't think you'll be able to get around defining the relationship between fields in some form. Take a look at this article and pay particular attention to how the mapping is defined, it may work for you.

    http://www.c-sharpcorner.com/UploadFile/rmcochran/elegant_dal05212006130957PM/elegant_dal.aspx

    0 讨论(0)
  • 2020-12-16 19:38

    I use ValueInjecter for this

    I'm doing like this:

     while (dr.Read())
      {
          var o = new User();
          o.InjectFrom<DataReaderInjection>(dr);
          yield return o;
      }
    

    you gonna need this ValueInjection for this to work:

    public class DataReaderInjection : KnownSourceValueInjection<IDataReader>
        {
            protected override void Inject(IDataReader source, object target, PropertyDescriptorCollection targetProps)
            {
                for (var i = 0; i < source.FieldCount; i++)
                {
                    var activeTarget = targetProps.GetByName(source.GetName(i), true);
                    if (activeTarget == null) continue;
    
                    var value = source.GetValue(i);
                    if (value == DBNull.Value) continue;
    
                    activeTarget.SetValue(target, value);
                }
            }
        }
    
    0 讨论(0)
  • 2020-12-16 19:43

    What about using Fluent Ado.net ?

    0 讨论(0)
  • 2020-12-16 19:47

    The easiest way I can think of offhand would be to supply a Func<T,T> delegate for converting each column and constructing your book.

    Alternatively, if you followed some conventions, you could potentially handle this via reflection. For example, if each column mapped to a property in the resulting object using the same name, and you restricted T in your Mapper to providing a constructable T, you could use reflection to set the value of each property to the value in the corresponding column.

    0 讨论(0)
  • 2020-12-16 19:50

    Well, i don't know if it fits here, but you could be using the yield keyword

    public static IEnumerable<T> MapObject(IDataReader dr, Func<IDataReader, T> convertFunction)
            {
                while (dr.Read())
                {
                    yield return convertFunction(dr);
                }
            }
    
    0 讨论(0)
  • 2020-12-16 19:54

    I would recommend that you'd use AutoMapper for this.

    0 讨论(0)
提交回复
热议问题