C# DapperでDB接続する方法
■環境
OS:Windows
言語:C♯
DB:SQL Server
フレームワーク:.NET Framework4.8
■事前準備
SQL Serverにtestテーブルを作成
create table test (
id int
, name varchar(20)
);
insert into test values (1, 'aaa');
insert into test values (2, 'bbb');
select * from test;
+------+------+
| id | name |
+------+------+
| 1 | aaa |
| 2 | bbb |
+------+------+
■ APIプロジェクトを作成
Visual Studioで下記の内容の「ASP.NET Webアプリケーション(.NET Framework)」を作成する
・空のプロジェクトテンプレートを選択
・Web APIにチェック
■APIコントローラークラスを作成
下記の手順で作成
①「Controllersフォルダ」を右クリック
②「追加」⇒「新規スキャフォールディングアイテムの追加」⇒「共有」⇒「Web API2 コントローラー -空」を押下し、コントローラークラスを任意の名前で作成する
■Modelsフォルダにエンティティクラスを作成
下記の手順で作成
①「Modelsフォルダ」を右クリック
②「追加」⇒「新しい項目」⇒「クラス」を選択して、Test.csを作成
テーブル構成と同じプロパティを作成
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DbConnection.Models
{
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
}
■Dapperをインストール
「ツール」⇒「NuGetパッケージマネージャー」⇒「ソリューションのNuGetパッケージの管理」⇒「参照」を押下し、「Dapper」を検索してインストール
■マッピングクラス作成
事前準備で作成したtestテーブルのマッピングクラスを作成
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DbConnection.Models
{
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
}
■DB接続
GETメソッドでDB接続する
まずはシンプルにする為にパラメーターは固定で記述
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using DbConnection.Models;
using Dapper;
namespace DbConnection.Controllers
{
public class SampleController : ApiController
{
public void Get()
{
//接続文字列
//string connectionStr = @"Server=[サーバー名];Database=[データベース名];Trusted_Connection=True;"; ※SQL Serverの場合
string connectionStr = @"Server=localhost;Database=sqlserver;Trusted_Connection=True;";
using (var connection = new SqlConnection(connectionStr))
{
//DB接続
connection.Open();
//クエリ
var query = "INSERT INTO test VALUES (@Id, @Name)";
///////////////////////////////////////////////////////
//パラメーター(1レコードの場合)
var param = new Test()
{
Id = 1
,
Name = "test1"
};
//クエリ実行
var retCd = connection.Execute(query, param);
///////////////////////////////////////////////////////
//パラメーター(複数レコードの場合)
var param2 = new List<Test>() {
new Test()
{
Id = 2
,Name = "test2"
},
new Test()
{
Id = 3
,Name = "test3"
}
};
//クエリ実行
var retCd2 = connection.Execute(query, param2);
}
}
}
}
■デバック実行
デバック実行で起動したURLに「api/[コントローラー名]」を追加
例)https://localhost:1111/api/sample
DBに登録されていることを確認
select * from test;
+------+--------+
| id | name |
+------+--------+
| 1 | test1 |
| 2 | test2 |
| 3 | test3 |
+------+--------+
トランザクションを設定する場合はこちら
C# DapperでDB接続する方法(トランザクション編)