あるプロジェクトに使うには Entity Framework は重厚すぎるという意見があり、micro-ORM である Dapper を試してみる。

Dapper は以下からダウンロードできる。
https://github.com/SamSaffron/dapper-dot-net

ダウンロードした中に「Dapper NET40」というフォルダがあり、その中に「SqlMapper.cs」というファイルがあるが、Dapper 本体はこの1ファイルのみである。したがってプロジェクトにこのファイルを追加するだけで Dapper が使える。

これからテストプロジェクトを作るが、その前に SQL Server にデータベースを用意しておく。データベース名は ORMTest とし、Product テーブルを作成する。データは適当に入れておく。
CREATE TABLE [dbo].[Product](
	[ProductId] [int] IDENTITY(1,1) NOT NULL,
	[Name] [nvarchar](50) NULL,
	[Price] [int] NULL,
	[SubCategoryId] [int] NULL,
 CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED 
(
	[ProductId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

次にプロジェクトを作成する。プロジェクト名は DapperTest1 とした。

Dapper 本体である SqlMapper.cs をプロジェクトに追加し、Form1.cs に以下を追加する。
using Dapper;

Form1 にButton と DataGridview を貼り付け、Button のクリックイベントで SQL Server からデータを取得し、DataGridview に表示することにする。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Dapper;
 
namespace DapperTest1
{
    public partial class Form1 : Form
    {
        private string connectionString = "Data Source=(local);Database=ORMTest;User ID=ORMTest_user;Password=ORMTest_password";
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void button1_Click(object sender, EventArgs e)
        {
            IEnumerable<Product> resultList = null;
 
            using (var conn = new SqlConnection(connectionString))
            {
                conn.Open();
                resultList = conn.Query<Product>(@"SELECT * FROM Product ORDER BY ProductId");
                conn.Close();
            }
 
            dataGridView1.DataSource = resultList;
        }
    }
 
    public class Product
    {
        public int ProductId { get; set; }
        public string Name { get; set; }
        public int Price { get; set; }
        public int SubCategoryId { get; set; }
    }
}

実行結果は以下のとおり。 dapper-1

以上。