看起來就是可以用 SQL 存取轉強行別的 輕量級 ORM 技術
安裝 Nuget – Dapper
建立資料庫及資料表 :
使用 dynamic 方式 :
string connectionString = "Server=.;Database=DapperDemo;Trusted_Connection=True;"; using (var sqlConnection = new SqlConnection(connectionString)) { var persons = sqlConnection.Query( "SELECT * FROM Person WHERE Age=@Age", new { Age = 32 }); foreach (var item in persons) { Console.WriteLine("{0}.{1}({2})", item.Id, item.Name, item.Age); } }
結果 :
建立 Model 存取 :
Person.cs
public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }
string connectionString = "Server=.;Database=DapperDemo;Trusted_Connection=True;"; using (var sqlConnection = new SqlConnection(connectionString)) { var persons = sqlConnection.Query<Person>( "SELECT * FROM Person WHERE Age=@Age", new { Age = 5 }); foreach (var item in persons) { Console.WriteLine("{0}.{1}({2})", item.Id, item.Name, item.Age); } }
結果 :