- A+
所属分类:.NET技术
以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)