Mapping IDataReader to object

This injection can be used to map the IDataReader to an instance of any type

The ReaderInjection

    public class ReaderInjection : KnownSourceValueInjection<IDataReader>
    {
        protected override void Inject(IDataReader source, object target)
        {
            for (var i = 0; i < source.FieldCount; i++)
            {
                var targetProp = target.GetProps().GetByName(source.GetName(i), true);
                if (targetProp == null) continue;

                var value = source.GetValue(i);
                if (value == DBNull.Value) value = null;

                targetProp.SetValue(target, value);
            }
        }
    }

The Test

using System;
using System.Collections.Generic;
using System.Data;
using NUnit.Framework;
using Omu.ValueInjecter;

namespace Tests
{
    public class IDataReaderInjectionTests
    {
        [Test]
        public void Main()
        {
            var persons = new List<Person>();
            var table = CreateSampleDataTable();
            var reader = table.CreateDataReader();

            while (reader.Read())
            {
                var p = new Person();

                p.InjectFrom<ReaderInjection>(reader);
                
                persons.Add(p);
            }

            persons.Count.IsEqualTo(5);
            persons[0].Id.IsEqualTo(100);
            persons[0].FirstName.IsEqualTo("Jeff");
            persons[0].LastName.IsEqualTo("Barnes");
            persons[1].Id.IsEqualTo(101);
            persons[1].FirstName.IsEqualTo("George");
            persons[1].LastName.IsEqualTo("Costanza");
        }

        public class Person
        {
            public int Id { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
        
        private static DataTable CreateSampleDataTable()
        {
            var table = new DataTable();

            table.Columns.Add("Id", typeof(int));
            table.Columns.Add("FirstName", typeof(string));
            table.Columns.Add("LastName", typeof(string));

            table.Rows.Add(100, "Jeff", "Barnes");
            table.Rows.Add(101, "George", "Costanza");
            table.Rows.Add(102, "Stewie", "Griffin");
            table.Rows.Add(103, "Stan", null);
            table.Rows.Add(104, "Eric", "Cartman");
            return table;
        }        
    }
}

Last edited Jun 1, 2011 at 7:03 AM by o, version 2

Comments

No comments yet.