Dapper.Lite 使用教程

以MySQL数据库为例

一. 安装

NuGet搜索Dapper.Lite并安装最新版本。

NuGet搜索MySqlConnector并安装最新版本。

也可以使用MySql.Data库,但MySqlConnector库性能更好。

二. 实现数据库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

    }
}

三. 创建实例

IDapperLite db = new DapperLite(
    "Data Source=localhost;Port=3306;User ID=root;Password=123456;Initial Catalog=litesql_test;Charset=utf8mb4;SslMode=none;Allow User Variables=True;",  
    new MySQLProvider());

四. 查询示例

SQL查询

IDbSession session = db.GetSession();
List<SysUser> list = session.Sql("select * from sys_user where id <= @Id and remark like @Remark", 20, "%测试%").ToList<SysUser>();
//或
list = session.Sql("select * from sys_user where id <= @Id and remark like @Remark", new { Id = 20, Remark = "%测试%" }).ToList<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)

NuGet地址

Dapper.Lite

如有问题加QQ群:497956447。

源码地址

https://gitee.com/s0611163/Dapper.Lite

https://github.com/0611163/Dapper.Lite

配套实体类生成器地址

https://gitee.com/s0611163/ModelGenerator

https://github.com/0611163/ModelGenerator

ClickHouse测试

https://gitee.com/s0611163/ClickHouseTest

posted @ 2023-06-03 21:22  0611163  阅读(267)  评论(4编辑  收藏  举报