以MySQL資料庫為例 # 一. 安裝 NuGet搜索Dapper.Lite並安裝最新版本。 ![](https://img2023.cnblogs.com/blog/174862/202306/174862-20230602155913303-757935399.jpg) NuGet搜索MySql ...
以MySQL資料庫為例
一. 安裝
NuGet搜索Dapper.Lite並安裝最新版本。
NuGet搜索MySql.Data並安裝最新版本。
二. 實現資料庫Provider
using Dapper.Lite;
using MySql.Data.MySqlClient;
using System.Data.Common;
namespace DAL
{
public class MySQLProvider : MySQLProviderBase, IDbProvider
{
#region 創建 DbConnection
public override DbConnection CreateConnection(string connectionString)
{
return new MySqlConnection(connectionString);
}
#endregion
#region 生成 DbParameter
public override DbParameter GetDbParameter(string name, object value)
{
return new MySqlParameter(name, value);
}
#endregion
}
}
三. 創建IDapperLiteClient實例
IDapperLiteClient db = new DapperLiteClient(
"Data Source=localhost;Port=3306;User ID=root;Password=123456;Initial Catalog=litesql_test;Charset=utf8mb4;SslMode=none;Allow User Variables=True;",
DBType.MySQL,
new MySQLProvider());
四. 查詢示例
SQL查詢
IDbSession session = db.GetSession();
ISqlString sql = session.Sql("select * from sys_user where id <= @Id and remark like @Remark", 20, "%測試%");
List<SysUser> list = sql.QueryList<SysUser>();
Lambda查詢
IDbSession session = db.GetSession();
List<SysUser> list = session.Queryable<SysUser>().Where(t => t.Id <= 20 && t.Remark.Contains("測試")).ToList();
SQL和Lambda表達式混寫
IDbSession session = db.GetSession();
List<BsOrder> list = session.Sql<BsOrder>(@"
select t.*, u.user_name as OrderUserName
from bs_order t
left join sys_user u on u.id = t.order_userid")
.Where(t => t.Amount > 100 && t.OrderTime > new DateTime(2022, 1, 1))
.Where<SysUser>(u => u.RealName == "張三")
.ToList();
更多示例
README.md (gitee)
wiki (gitee)
README.md (github)
wiki (github)