Dapper 的使用
以下範例示範 Dapper 基本的使用
一、資料準備
1 | -- create table |
二、開一個 .net core ConsoleApp 專案
三、於 NuGet 安裝 dapper 與其他相關套件,指令如下
1 | $ Install-Package Dapper |
四、程式實作使用 Dapper 技術讀取資料庫
建立資料庫連線
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21using Microsoft.Extensions.Configuration;
using System.Data.SqlClient;
namespace ConsoleApp1
{
public class DatabaseContext
{
private readonly string _connectionString;
public DatabaseContext(IConfiguration configuration)
{
_connectionString = configuration.GetConnectionString("DefaultConnection");
}
public SqlConnection GetConnection()
{
return new SqlConnection(_connectionString);
}
}
}而連線參數的 appsettings.json 設定檔內容大致如下
1
2
3
4
5{
"ConnectionStrings": {
"DefaultConnection": "Data Source=instance;Database=test_db;Trusted_Connection=False;MultipleActiveResultSets=true;User ID=sa;Password=pwd"
}
}準備對應到資料表的類別
1
2
3
4
5
6
7
8
9namespace ConsoleApp1
{
public class StudentScore
{
public string student_name { get; set; }
public string subject { get; set; }
public int score { get; set; }
}
}建立一 repository ,並使用 Dapper 在資料庫查詢相關資料
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27using Dapper;
namespace ConsoleApp1
{
public class StudentRepository
{
private readonly DatabaseContext _context;
public StudentRepository(DatabaseContext context)
{
_context = context;
}
public IEnumerable<StudentScore> GetStudentScores()
{
using (var connection = _context.GetConnection())
{
connection.Open();
string query = @"select std.student_name, ss.subject, ss.score
from student std
join score ss on std.student_id = ss.student_id";
return connection.Query<StudentScore>(query);
}
}
}
}將該 repository 註冊進服務中
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27using ConsoleApp1;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
class Program
{
static void Main(string[] args)
{
var configuration = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var services = new ServiceCollection()
.AddSingleton<IConfiguration>(configuration)
.AddScoped<DatabaseContext>()
.AddScoped<StudentRepository>()
.BuildServiceProvider();
var repository = services.GetRequiredService<StudentRepository>();
var results = repository.GetStudentScores();
foreach (var s in results)
{
Console.WriteLine($"student_name: {s.student_name}, subject: {s.subject}, score: {s.score}");
}
}
}
參考資料:
Dapper 筆記
Dapper ORM