10
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DataReader からクラスにマッピングのサンプル

Last updated at Posted at 2015-02-14

#はじめに
IEnumerable から IDataReader へ変換を作成していて、もっと簡単にデータを変換するためDataReaderから指定したクラスにデータを格納するクラスを作ると簡単にデータを変換できると考えサンプルを作成した。
DbExecutorも良かったが、直接クラスに格納した方が手間が省ける。
パラメータもDbExecutor のソースを読んで追加したり、nullの対応をすると便利なツールが作成出来そうだ。
#サンプルコード

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
using System.Threading.Tasks;
using SampleDataReader.Properties;

namespace SampleDataReader
{

    class DataReaderEnumerable<TSource> 
    {
        private readonly string _sql;
        private readonly string _connectString;
        private readonly List<PropertyInfo> listProp = new List<PropertyInfo>();

        public DataReaderEnumerable(string sql, string connectString)
        {
            _sql = sql;
            _connectString = connectString;
            foreach (var prop in typeof(TSource).GetProperties())
            {
                listProp.Add(prop);
            }
        }

        public IEnumerable<TSource> AsEnumerable()
        {
            using (var conn = new SqlConnection(_connectString))
            {
                conn.Open();
                var cmd = new SqlCommand(_sql, conn);
                using (var rd = cmd.ExecuteReader())
                {
                    while (rd.Read())
                    {
                        TSource cls = Activator.CreateInstance<TSource>();
                        foreach (var fld in listProp)
                            fld.SetValue(cls, rd[fld.Name]);
                        yield return cls;
                    }
                }
            }
        }
    }

    class SampleTable
    {
        public int Field1 { get; set; }
        public string Field2 { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {

            string sql = "SELECT * FROM SampleTable";
            string constr = Settings.Default.xxxConnectionString;
            var cls = new DataReaderEnumerable<SampleTable>(sql, constr);
            foreach (var row in cls.AsEnumerable())
            {
                Console.WriteLine("{0} {1}", row.Field1, row.Field2);
            }

        }
    }
}```
10
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
16

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?