using Dapper; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks;
namespace DapperExample.Dapper { public class DataControl : IDisposable { private IDbConnection db = null; private string _connectStr;
//建構子初始化連線字串/DB連接 public DataControl() { // 自行替換資料庫連結字串 string connectionStr = @"Server=.\SQLExpress;Database=Orders;Trusted_Connection=True;ConnectRetryCount=0"; _connectStr = connectionStr; db = new SqlConnection(_connectStr); }
//共用新增刪除修改方法 public int Execute(string sql, object param) { return db.Execute(sql, param); }
//釋放連接 public void Dispose() { db.Dispose(); } } }
說明: 唯一要改的在20行要套入自己的資料庫連結字串。
2.再來建立對應的資料表Model
~/Models/Customer.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
using System.ComponentModel.DataAnnotations; namespace DapperExample.Models { public class Customer { [Display(Name = "編號")] public string Number { get; set; } [Display(Name = "名子")] [Required(ErrorMessage = "名字不可為空")] public string Name { get; set; } [Display(Name = "電話")] public string Tel { get; set; } } }
using DapperExample.Dapper; using DapperExample.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks;
namespace DapperExample.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger) { _logger = logger; }
public IActionResult Index() { Customer customer; // 使用using,區塊結束後會自動執行Dispose using (DataControl dc = new DataControl()) { string number = "U001"; string sql = @"SELECT * FROM Customers WHERE number = @number"; var result = dc.Query<Customer>(sql, new { number });//執行DataControl的Query方法 customer = result.First(); } return View(customer); }
<div class="text-center"> <h1 class="display-4">Welcome</h1> <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p> </div> <ul> <li>@Model.Number</li> <li>@Model.Name</li> <li>@Model.Tel</li> </ul>