README.md 59.1 KB
Newer Older
s0611163's avatar
初始  
s0611163 已提交
1 2 3 4 5 6
# LiteSql

## 简介

一款使用原生SQL查询的轻量级ORM,支持Oracle、MSSQL、MySQL、PostgreSQL、SQLite、Access数据库。

s0611163's avatar
s0611163 已提交
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
## 经典示例

```C#
DateTime? startTime = null;

using (var session = LiteSqlFactory.GetSession())
{
    session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL

    List<SysUser> list = session.CreateSql(@"
        select * from sys_user t where t.id <= @Id", new { Id = 20 })

        .Append(@" and t.create_userid = @CreateUserId 
            and t.password like @Password
            and t.id in @Ids",
            new
            {
                CreateUserId = "1",
                Password = "%345%",
                Ids = session.CreateSql().ForList(new List<int> { 1, 2, 9, 10, 11 })
            })

s0611163's avatar
s0611163 已提交
29
        .AppendIf(startTime.HasValue, " and t.create_time >= @StartTime ", new { StartTime = startTime })
s0611163's avatar
s0611163 已提交
30

s0611163's avatar
s0611163 已提交
31
        .Append(" and t.create_time <= @EndTime ", new { EndTime = new DateTime(2022, 8, 1) })
s0611163's avatar
s0611163 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46

        .QueryList<SysUser>();

    long id = session.CreateSql("select id from sys_user where id=@Id", new { Id = 1 })
        .QuerySingle<long>();
    Assert.IsTrue(id == 1);

    foreach (SysUser item in list)
    {
        Console.WriteLine(ModelToStringUtil.ToString(item));
    }
    Assert.IsTrue(list.Count > 0);
}
```

s0611163's avatar
初始  
s0611163 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
## 特点

1. 支持Oracle、MSSQL、MySQL、PostgreSQL、SQLite五种数据库
2. 可以很方便地支持任意关系数据库
3. 有配套的Model生成器
4. insert、update、delete操作无需写SQL
5. 查询使用原生SQL
6. 查询结果通过映射转成实体类或实体类集合
7. 支持参数化查询,通过SqlString类提供非常方便的参数化查询
8. 支持连接多个数据源
9. 支持手动分表
10. 单表查询、单表分页查询、简单的联表分页查询支持Lambda表达式
11. 支持原生SQL和Lambda表达式混写

## 优点

1. 比较简单,学习成本低
2. 查询使用原生SQL

## 缺点

1. 对Lambda表达式的支持比较弱
2. 复杂查询不支持Lambda表达式(子查询、分组统计查询、嵌套查询等不支持)

## 建议

1. 单表查询、简单的连表查询可以使用Lambda表达式
2. 复杂查询建议使用原生SQL
3. 如果出现不支持的Lambda表达式写法,请使用原生SQL替代

## 开发环境

1. VS2022
2. 测试工程使用.NET Framework 4.5.2

## 配套Model生成器地址:

[https://gitee.com/s0611163/ModelGenerator](https://gitee.com/s0611163/ModelGenerator)

## Dapper版

使用ADO.NET操作数据库改成了使用Dapper操作数据库

[https://gitee.com/s0611163/Dapper.LiteSql/](https://gitee.com/s0611163/Dapper.LiteSql/)

## 作者邮箱

    651029594@qq.com

## 使用步骤

1. 安装LiteSql

```text
s0611163's avatar
s0611163 已提交
101
Install-Package Dapper.LiteSql -Version 1.6.13
s0611163's avatar
初始  
s0611163 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
```

2. 安装对应的数据库引擎

```text
Install-Package MySql.Data -Version 6.9.12
```

3. 实现对应的数据库Provider

注意:各实现方法一定要加上override关键字以重写基类的方法

```C#
using LiteSql;
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

    }
}

```

4. 定义LiteSqlFactory类

```C#
using LiteSql;
using System.Configuration;
using System.Threading.Tasks;

namespace DAL
{
    public class LiteSqlFactory
    {
        #region 变量
s0611163's avatar
优化  
s0611163 已提交
154
        private static ILiteSqlClient _liteSqlClient = new LiteSqlClient(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(), DBType.MySQL, new MySQLProvider());
s0611163's avatar
初始  
s0611163 已提交
155 156 157 158 159 160
        #endregion

        #region 获取 ISession
        /// <summary>
        /// 获取 ISession
        /// </summary>
s0611163's avatar
s0611163 已提交
161 162
        /// <param name="splitTableMapping">分表映射</param>
        public static ISession GetSession(SplitTableMapping splitTableMapping = null)
s0611163's avatar
初始  
s0611163 已提交
163
        {
s0611163's avatar
s0611163 已提交
164
            return _liteSqlClient.GetSession(splitTableMapping);
s0611163's avatar
初始  
s0611163 已提交
165 166 167 168 169 170 171
        }
        #endregion

        #region 获取 ISession (异步)
        /// <summary>
        /// 获取 ISession (异步)
        /// </summary>
s0611163's avatar
s0611163 已提交
172 173
        /// <param name="splitTableMapping">分表映射</param>
        public static async Task<ISession> GetSessionAsync(SplitTableMapping splitTableMapping = null)
s0611163's avatar
初始  
s0611163 已提交
174
        {
s0611163's avatar
s0611163 已提交
175
            return await _liteSqlClient.GetSessionAsync(splitTableMapping);
s0611163's avatar
初始  
s0611163 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        }
        #endregion

    }
}
```

## 配套Model生成器

### 使用Model生成器生成实体类

1. 实体类放在Models文件夹中
2. 扩展实体类放在ExtModels文件夹中
3. 实体类和扩展实体类使用partial修饰,实际上是一个类,放在不同的文件中
4. 如果需要添加自定义属性,请修改ExtModels,不要修改Models

#### 实体类示例

```C#
/// <summary>
/// 订单表
/// </summary>
[Serializable]
[Table("bs_order")]
public partial class BsOrder
{

    /// <summary>
    /// 主键
    /// </summary>
    [Key]
    [Column("id")]
    public string Id { get; set; }

    /// <summary>
    /// 订单时间
    /// </summary>
    [Column("order_time")]
    public DateTime OrderTime { get; set; }

    /// <summary>
    /// 订单金额
    /// </summary>
    [Column("amount")]
    public decimal? Amount { get; set; }

    /// <summary>
    /// 下单用户
    /// </summary>
    [Column("order_userid")]
    public long OrderUserid { get; set; }

    /// <summary>
    /// 订单状态(0草稿 1已下单 2已付款 3已发货 4完成)
    /// </summary>
    [Column("status")]
    public int Status { get; set; }

    /// <summary>
    /// 备注
    /// </summary>
    [Column("remark")]
    public string Remark { get; set; }

    /// <summary>
    /// 创建者ID
    /// </summary>
    [Column("create_userid")]
    public string CreateUserid { get; set; }

    /// <summary>
    /// 创建时间
    /// </summary>
    [Column("create_time")]
    public DateTime CreateTime { get; set; }

    /// <summary>
    /// 更新者ID
    /// </summary>
    [Column("update_userid")]
    public string UpdateUserid { get; set; }

    /// <summary>
    /// 更新时间
    /// </summary>
    [Column("update_time")]
    public DateTime? UpdateTime { get; set; }

}
```

### 修改扩展实体类

1. 修改扩展实体类,添加自定义属性
2. 下面的扩展实体类中,查询时OrderUserRealName会被自动填充,查询SQL:select t.*, u.real_name as OrderUserRealName from ......
3. DetailList不会被自动填充,需要手动查询

#### 扩展实体类示例

```C#
/// <summary>
/// 订单表
/// </summary>
public partial class BsOrder
{
    /// <summary>
    /// 订单明细集合
    /// </summary>
    public List<BsOrderDetail> DetailList { get; set; }

    /// <summary>
    /// 下单用户姓名
    /// </summary>
    public string OrderUserRealName { get; set; }

    /// <summary>
    /// 下单用户名
    /// </summary>
    public string OrderUserName { get; set; }
}
```

## 增删改查示例

### 添加

```C#
public void Insert(SysUser info)
{
    using (var session = LiteSqlFactory.GetSession())
    {
        session.Insert(info);
    }
}
```

s0611163's avatar
s0611163 已提交
312 313 314 315 316 317 318 319 320 321 322 323
### 添加并返回ID

```C#
public void Insert(SysUser info)
{
    using (var session = LiteSqlFactory.GetSession())
    {
        long id = session.InsertReturnId(info, "select @@IDENTITY");
    }
}
```

s0611163's avatar
初始  
s0611163 已提交
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
### 批量添加

```C#
public void Insert(List<SysUser> list)
{
    using (var session = LiteSqlFactory.GetSession())
    {
        session.Insert(list);
    }
}
```

### 修改

```C#
public void Update(SysUser info)
{
    using (var session = LiteSqlFactory.GetSession())
    {
        session.Update(info);
    }
}
```

### 批量修改

```C#
public void Update(List<SysUser> list)
{
    using (var session = LiteSqlFactory.GetSession())
    {
        session.Update(list);
    }
}
```

### 修改时只更新数据有变化的字段

```C#
using (var session = LiteSqlFactory.GetSession())
{
    session.AttachOld(user); //附加更新前的旧数据,只更新数据发生变化的字段,提升更新性能

    user.UpdateUserid = "1";
    user.Remark = "测试修改用户" + _rnd.Next(1, 100);
    user.UpdateTime = DateTime.Now;

    session.Update(user);
}
```

```C#
using (var session = LiteSqlFactory.GetSession())
{
    session.AttachOld(userList); //附加更新前的旧数据,只更新数据发生变化的字段,提升更新性能

    foreach (SysUser user in userList)
    {
        user.Remark = "测试修改用户" + _rnd.Next(1, 10000);
        user.UpdateUserid = "1";
        user.UpdateTime = DateTime.Now;
    }

    session.Update(userList);
}
```

### 删除


```C#
public void Delete(string id)
{
    using (var session = LiteSqlFactory.GetSession())
    {
        session.DeleteById<SysUser>(id);
    }
}
```

### 条件删除

```C#
using (var session = LiteSqlFactory.GetSession())
{
    session.DeleteByCondition<SysUser>(string.Format("id>=12"));
}
```

### 查询单个记录

```C#
public SysUser Get(string id)
{
    using (var session = LiteSqlFactory.GetSession())
    {
        return session.QueryById<SysUser>(id);
    }
}
```

```C#
using (var session = LiteSqlFactory.GetSession())
{
    return session.Query<SysUser>("select * from sys_user");
}
```

### 简单查询

```C#
using (var session = LiteSqlFactory.GetSession())
{
    string sql = "select * from CARINFO_MERGE";
    List<CarinfoMerge> result = session.QueryList<CarinfoMerge>(sql);
}
```

### 条件查询

```C#
public List<BsOrder> GetList(int? status, string remark, DateTime? startTime, DateTime? endTime)
{
    using (var session = LiteSqlFactory.GetSession())
    {
s0611163's avatar
s0611163 已提交
449
        ISqlString sql = session.CreateSql(@"
s0611163's avatar
初始  
s0611163 已提交
450 451 452 453 454 455 456
            select t.*, u.real_name as OrderUserRealName
            from bs_order t
            left join sys_user u on t.order_userid=u.id
            where 1=1");

        sql.AppendIf(status.HasValue, " and t.status=@status", status);

457
        sql.AppendIf(!string.IsNullOrWhiteSpace(remark), " and t.remark like @remark", "%" + remark + "%");
s0611163's avatar
初始  
s0611163 已提交
458

459
        sql.AppendIf(startTime.HasValue, " and t.order_time >= @startTime ", startTime);
s0611163's avatar
初始  
s0611163 已提交
460

461
        sql.AppendIf(endTime.HasValue, " and t.order_time <= @endTime ", endTime);
s0611163's avatar
初始  
s0611163 已提交
462 463 464

        sql.Append(" order by t.order_time desc, t.id asc ");

s0611163's avatar
s0611163 已提交
465
        List<BsOrder> list = session.QueryList<BsOrder>(sql);
s0611163's avatar
初始  
s0611163 已提交
466 467 468 469 470 471 472 473 474 475 476 477
        return list;
    }
}
```

### 条件查询(SQL参数支持匿名对象)

```C#
public List<BsOrder> GetList(int? status, string remark, DateTime? startTime, DateTime? endTime)
{
    using (var session = LiteSqlFactory.GetSession())
    {
s0611163's avatar
s0611163 已提交
478
        ISqlString sql = session.CreateSql(@"
s0611163's avatar
初始  
s0611163 已提交
479 480 481 482 483
            select t.*, u.real_name as OrderUserRealName
            from bs_order t
            left join sys_user u on t.order_userid=u.id
            where 1=1");

484
        sql.AppendIf(status.HasValue, " and t.status=@Status", new { Status = status });
s0611163's avatar
初始  
s0611163 已提交
485

486
        sql.AppendIf(!string.IsNullOrWhiteSpace(remark), " and t.remark like @Remark", new { Remark = "%" + remark + "%" });
s0611163's avatar
初始  
s0611163 已提交
487

488
        sql.AppendIf(startTime.HasValue, " and t.order_time >= @StartTime ", new { StartTime = startTime } });
s0611163's avatar
初始  
s0611163 已提交
489

490
        sql.AppendIf(endTime.HasValue, " and t.order_time <= @EndTime ", endTime });
s0611163's avatar
初始  
s0611163 已提交
491 492 493

        sql.Append(" order by t.order_time desc, t.id asc ");

s0611163's avatar
s0611163 已提交
494
        List<BsOrder> list = session.QueryList<BsOrder>(sql);
s0611163's avatar
初始  
s0611163 已提交
495 496 497 498 499 500 501 502 503 504 505 506
        return list;
    }
}
```

### 分页查询

```C#
public List<BsOrder> GetListPage(ref PageModel pageModel, int? status, string remark, DateTime? startTime, DateTime? endTime)
{
    using (var session = LiteSqlFactory.GetSession())
    {
s0611163's avatar
s0611163 已提交
507
        ISqlString sql = session.CreateSql(@"
s0611163's avatar
初始  
s0611163 已提交
508 509 510 511 512 513 514
            select t.*, u.real_name as OrderUserRealName
            from bs_order t
            left join sys_user u on t.order_userid=u.id
            where 1=1");

        sql.AppendIf(status.HasValue, " and t.status=@status", status);

515
        sql.AppendIf(!string.IsNullOrWhiteSpace(remark), " and t.remark like @remark", "%" + remark + "%");
s0611163's avatar
初始  
s0611163 已提交
516

517
        sql.AppendIf(startTime.HasValue, " and t.order_time >= @startTime ", startTime);
s0611163's avatar
初始  
s0611163 已提交
518

519
        sql.AppendIf(endTime.HasValue, " and t.order_time <= @endTime ", endTime);
s0611163's avatar
初始  
s0611163 已提交
520 521 522

        string orderby = " order by t.order_time desc, t.id asc ";
        
s0611163's avatar
s0611163 已提交
523 524
        pageModel.TotalRows = session.QueryCount(sql);
        return session.QueryPage<BsOrder>(sql, orderby, pageModel.PageSize, pageModel.CurrentPage);
s0611163's avatar
初始  
s0611163 已提交
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
    }
}
```


### 事务

```C#
public string Insert(BsOrder order, List<BsOrderDetail> detailList)
{
    using (var session = LiteSqlFactory.GetSession())
    {
        try
        {
            session.BeginTransaction();

            order.Id = Guid.NewGuid().ToString("N");
            order.CreateTime = DateTime.Now;

            decimal amount = 0;
            foreach (BsOrderDetail detail in detailList)
            {
                detail.Id = Guid.NewGuid().ToString("N");
                detail.OrderId = order.Id;
                detail.CreateTime = DateTime.Now;
                amount += detail.Price * detail.Quantity;
                session.Insert(detail);
            }
            order.Amount = amount;

            session.Insert(order);

            session.CommitTransaction();

            return order.Id;
        }
        catch (Exception ex)
        {
            session.RollbackTransaction();
            Console.WriteLine(ex.Message + "\r\n" + ex.StackTrace);
            throw ex;
        }
    }
}
```

### 异步查询

```C#
public async Task<List<BsOrder>> GetListPageAsync(PageModel pageModel, int? status, string remark, DateTime? startTime, DateTime? endTime)
{
    using (var session = await LiteSqlFactory.GetSessionAsync())
    {
s0611163's avatar
s0611163 已提交
578
        ISqlString sql = session.CreateSql(@"
s0611163's avatar
初始  
s0611163 已提交
579 580 581 582 583 584 585
            select t.*, u.real_name as OrderUserRealName
            from bs_order t
            left join sys_user u on t.order_userid=u.id
            where 1=1");

        sql.AppendIf(status.HasValue, " and t.status=@status", status);

586
        sql.AppendIf(!string.IsNullOrWhiteSpace(remark), " and t.remark like @remark", "%" + remark + "%");
s0611163's avatar
初始  
s0611163 已提交
587

588
        sql.AppendIf(startTime.HasValue, " and t.order_time >= @startTime ", startTime);
s0611163's avatar
初始  
s0611163 已提交
589

590
        sql.AppendIf(endTime.HasValue, " and t.order_time <= @endTime ", endTime);
s0611163's avatar
初始  
s0611163 已提交
591 592 593

        string orderby = " order by t.order_time desc, t.id asc ";
        
s0611163's avatar
s0611163 已提交
594
        var countResult = await session.QueryCountAsync(sql, pageModel.PageSize);
s0611163's avatar
初始  
s0611163 已提交
595
        pageModel.TotalRows = countResult.Count;
s0611163's avatar
s0611163 已提交
596
        return await session.QueryPageAsync<BsOrder>(sql, orderby, pageModel.PageSize, pageModel.CurrentPage);
s0611163's avatar
初始  
s0611163 已提交
597 598 599 600 601 602 603 604 605 606 607
    }
}
```

### 条件查询(使用 ForContains、ForStartsWith、ForEndsWith、ForDateTime、ForList 等辅助方法)

```C#
public List<BsOrder> GetListExt(int? status, string remark, DateTime? startTime, DateTime? endTime, string ids)
{
    using (var session = LiteSqlFactory.GetSession())
    {
s0611163's avatar
s0611163 已提交
608
        ISqlString sql = session.CreateSql(@"
s0611163's avatar
初始  
s0611163 已提交
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625
            select t.*, u.real_name as OrderUserRealName
            from bs_order t
            left join sys_user u on t.order_userid=u.id
            where 1=1");

        sql.AppendIf(status.HasValue, " and t.status=@status", status);

        sql.AppendIf(!string.IsNullOrWhiteSpace(remark), " and t.remark like @remark", sql.ForContains(remark));

        sql.AppendIf(startTime.HasValue, " and t.order_time >= @startTime ", sql.ForDateTime(startTime.Value));

        sql.AppendIf(endTime.HasValue, " and t.order_time <= @endTime ", sql.ForDateTime(endTime.Value));

        sql.Append(" and t.id in @ids ", sql.ForList(ids.Split(',').ToList()));

        sql.Append(" order by t.order_time desc, t.id asc ");

s0611163's avatar
s0611163 已提交
626
        List<BsOrder> list = session.QueryList<BsOrder>(sql);
s0611163's avatar
初始  
s0611163 已提交
627 628 629 630 631 632 633 634 635 636 637 638 639 640
        return list;
    }
}
```

### 使用Lambda表达式单表查询

单表分页查询使用ToPageList替换ToList即可

```C#
public void TestQueryByLambda6()
{
    using (var session = LiteSqlFactory.GetSession())
    {
s0611163's avatar
s0611163 已提交
641
        ISqlQueryable<BsOrder> sql = session.Queryable<BsOrder>();
s0611163's avatar
初始  
s0611163 已提交
642 643 644

        string remark = "测试";

s0611163's avatar
s0611163 已提交
645 646 647 648
        List<BsOrder> list = sql.WhereIf(!string.IsNullOrWhiteSpace(remark),
            t => t.Remark.Contains(remark)
            && t.CreateTime < DateTime.Now
            && t.CreateUserid == "10")
s0611163's avatar
初始  
s0611163 已提交
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667

            .OrderByDescending(t => t.OrderTime).OrderBy(t => t.Id)
            .ToList();

        foreach (BsOrder item in list)
        {
            Console.WriteLine(ModelToStringUtil.ToString(item));
        }
    }
}
```

### 使用Lambda表达式联表分页查询(简单的联表查询,复杂情况请使用原生SQL或原生SQL和Lambda表达式混写)

```C#
public void TestQueryByLambda7()
{
    using (var session = LiteSqlFactory.GetSession())
    {
s0611163's avatar
s0611163 已提交
668
        ISqlQueryable<BsOrder> sql = session.Queryable<BsOrder>();
s0611163's avatar
初始  
s0611163 已提交
669 670 671 672

        int total;
        List<string> idsNotIn = new List<string>() { "100007", "100008", "100009" };

s0611163's avatar
s0611163 已提交
673
        List<BsOrder> list = sql
s0611163's avatar
初始  
s0611163 已提交
674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
            .Select<SysUser>(u => u.UserName, t => t.OrderUserName)
            .Select<SysUser>(u => u.RealName, t => t.OrderUserRealName)
            .LeftJoin<SysUser>((t, u) => t.OrderUserid == u.Id)
            .LeftJoin<BsOrderDetail>((t, d) => t.Id == d.OrderId)
            .Where<SysUser, BsOrderDetail>((t, u, d) => t.Remark.Contains("订单") && u.CreateUserid == "1" && d.GoodsName != null)
            .WhereIf<BsOrder>(true, t => t.Remark.Contains("测试"))
            .WhereIf<BsOrder>(true, t => !idsNotIn.Contains(t.Id))
            .WhereIf<SysUser>(true, u => u.CreateUserid == "1")
            .OrderByDescending(t => t.OrderTime).OrderBy(t => t.Id)
            .ToPageList(1, 20, out total);

        foreach (BsOrder item in list)
        {
            Console.WriteLine(ModelToStringUtil.ToString(item));
        }
    }
}
```

### 原生SQL和Lambda表达式混写

```C#
public void TestQueryByLambda9()
{
    using (var session = LiteSqlFactory.GetSession())
    {
s0611163's avatar
s0611163 已提交
700
        ISqlQueryable<BsOrder> sql = session.CreateSql<BsOrder>(@"
s0611163's avatar
初始  
s0611163 已提交
701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
            select t.*, u.real_name as OrderUserRealName
            from bs_order t
            left join sys_user u on t.order_userid=u.id
            where 1=1");

        List<BsOrder> list = sql.Where(t => t.Status == int.Parse("0")
            && t.Status == new BsOrder().Status
            && t.Remark.Contains("订单")
            && t.Remark != null
            && t.OrderTime >= new DateTime(2010, 1, 1)
            && t.OrderTime <= DateTime.Now.AddDays(1))
            .WhereIf<SysUser>(true, u => u.CreateTime < DateTime.Now)
            .OrderByDescending(t => t.OrderTime).OrderBy(t => t.Id)
            .ToList();

        foreach (BsOrder item in list)
        {
            Console.WriteLine(ModelToStringUtil.ToString(item));
        }
    }
}
```

s0611163's avatar
s0611163 已提交
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
```C#
DateTime? startTime = null;

using (var session = LiteSqlFactory.GetSession())
{
    session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL

    List<SysUser> list = session.Queryable<SysUser>()

        .Append<SysUser>(@" where t.create_userid = @CreateUserId 
            and t.password like @Password
            and t.id in @Ids",
            new
            {
                CreateUserId = "1",
                Password = "%345%",
                Ids = session.CreateSql().ForList(new List<int> { 1, 2, 9, 10, 11 })
            })

        .Where(t => !t.UserName.Contains("管理员"))

        .Append<SysUser>(@" and t.create_time >= @StartTime", new { StartTime = new DateTime(2020, 1, 1) })

        .Where<SysUser>(t => t.Id <= 20)

        .AppendIf(startTime.HasValue, " and t.create_time >= @StartTime ", new { StartTime = startTime })

        .Append(" and t.create_time <= @EndTime ", new { EndTime = new DateTime(2022, 8, 1) })

        .QueryList<SysUser>();

    long id = session.Queryable<SysUser>().Where(t => t.Id == 1).First().Id;
    Assert.IsTrue(id == 1);

    foreach (SysUser item in list)
    {
        Console.WriteLine(ModelToStringUtil.ToString(item));
    }
    Assert.IsTrue(list.Count > 0);
}
```

766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
### 拼接子SQL

```C#
using (var session = LiteSqlFactory.GetSession())
{
    session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL

    var subSql = session.CreateSql<SysUser>("select t.Id from sys_user t").Where(t => !t.RealName.Contains("管理员"));

    var subSql2 = session.CreateSql<SysUser>("select t.Id from sys_user t").Where(t => t.Id <= 20);

    var sql = session.Queryable<SysUser>()

        .Where(t => t.Password.Contains("345"))

        .Append(" and id in ", subSql)

        .Append<SysUser>(@" and t.create_time >= @StartTime", new { StartTime = new DateTime(2020, 1, 1) })

        .Append<SysUser>(" and id in ", subSql2)

        .Where(t => t.Password.Contains("234"));

    var sql2 = session.Queryable<SysUser>().Where(t => t.RealName.Contains("管理员"));

    sql.Append(" union all ", sql2);

    List<SysUser> list = sql.QueryList<SysUser>();

    foreach (SysUser item in list)
    {
        Console.WriteLine(ModelToStringUtil.ToString(item));
    }
    Assert.IsTrue(list.Count > 0);
    Assert.IsTrue(list.Count(t => t.RealName.Contains("管理员")) > 0);
    Assert.IsTrue(list.Count(t => t.Id > 20) == 0);
}
```

### 拼接子查询

```C#
using (var session = LiteSqlFactory.GetSession())
{
    session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL

    List<SysUser> list = session.CreateSql<SysUser>()
        .Select(session.CreateSql("count(id) as Count"))
        .Select(t => new
        {
            t.RealName,
            t.CreateUserid
        })
        .Where(t => t.Id >= 0)
        .Append<SysUser>("group by t.real_name, t.create_userid")
        .Append<SysUser>("having real_name like @Name1 or real_name like @Name2", new
        {
            Name1 = "%管理员%",
            Name2 = "%测试%"
        })
        .ToList();

    foreach (SysUser item in list)
    {
        Console.WriteLine(ModelToStringUtil.ToString(item));
    }
    Assert.IsTrue(list.Count > 0);
}
```

```C#
using (var session = LiteSqlFactory.GetSession())
{
    session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL

    List<SysUser> list = session.CreateSql<SysUser>()
        .Select(t => new
        {
            t.RealName,
            t.CreateUserid
        })
        .Select(session.CreateSql(@"(
                select count(1) 
                from bs_order o 
                where o.order_userid = t.id
                and o.status = @Status
            ) as OrderCount", new { Status = 0 }))
        .Where(t => t.Id >= 0)
        .ToList();

    foreach (SysUser item in list)
    {
        Console.WriteLine(ModelToStringUtil.ToString(item));
    }
    Assert.IsTrue(list.Count > 0);
}
```

s0611163's avatar
初始  
s0611163 已提交
864 865 866 867 868 869 870 871 872 873 874 875 876 877
## 手动分表

### 定义LiteSqlFactory类

```C#
using LiteSql;
using System.Configuration;
using System.Threading.Tasks;

namespace DAL
{
    public class LiteSqlFactory
    {
        #region 变量
s0611163's avatar
优化  
s0611163 已提交
878
        private static ILiteSqlClient _liteSqlClient = new LiteSqlClient(ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString(), DBType.MySQL, new MySQLProvider());
s0611163's avatar
初始  
s0611163 已提交
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917
        #endregion

        #region 获取 ISession
        /// <summary>
        /// 获取 ISession
        /// </summary>
        /// <param name="splitTableMapping">分表映射</param>
        public static ISession GetSession(SplitTableMapping splitTableMapping = null)
        {
            return _liteSqlClient.GetSession(splitTableMapping);
        }
        #endregion

        #region 获取 ISession (异步)
        /// <summary>
        /// 获取 ISession (异步)
        /// </summary>
        /// <param name="splitTableMapping">分表映射</param>
        public static async Task<ISession> GetSessionAsync(SplitTableMapping splitTableMapping = null)
        {
            return await _liteSqlClient.GetSessionAsync(splitTableMapping);
        }
        #endregion

    }
}
```

### 数据插入

```C#
SplitTableMapping splitTableMapping = new SplitTableMapping(typeof(SysUser), "sys_user_202208");

using (var session = LiteSqlFactory.GetSession(splitTableMapping))
{
    session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL

    session.Insert(user);

s0611163's avatar
s0611163 已提交
918
    user.Id = session.QuerySingle<long>("select @@IDENTITY");
s0611163's avatar
初始  
s0611163 已提交
919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
    Console.WriteLine("插入成功, user.Id=" + user.Id);
}
```

### 数据更新

```C#
SplitTableMapping splitTableMapping = new SplitTableMapping(typeof(SysUser), "sys_user_202208");

using (var session = LiteSqlFactory.GetSession(splitTableMapping))
{
    session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL

    session.AttachOld(user); //附加更新前的旧数据,只更新数据发生变化的字段,提升更新性能

    user.UpdateUserid = "1";
    user.Remark = "测试修改分表数据" + _rnd.Next(1, 100);
    user.UpdateTime = DateTime.Now;

    session.Update(user);
}
```

### 数据删除

```C#
SplitTableMapping splitTableMapping = new SplitTableMapping(typeof(SysUser), "sys_user_202208");
using (var session = LiteSqlFactory.GetSession(splitTableMapping))
{
    session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL

    int deleteCount = session.DeleteByCondition<SysUser>(string.Format("id>20"));
    Console.WriteLine(deleteCount + "条数据已删除");
    int deleteCount2 = session.DeleteById<SysUser>(10000);
    Console.WriteLine(deleteCount2 + "条数据已删除");
}
```

### 数据查询

```C#
using (var session = LiteSqlFactory.GetSession(splitTableMapping))
{
    session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL

s0611163's avatar
s0611163 已提交
964
    ISqlQueryable<SysUser> sql = session.Queryable<SysUser>();
s0611163's avatar
初始  
s0611163 已提交
965

s0611163's avatar
s0611163 已提交
966
    List<SysUser> list = sql.Where(t => t.Id < 10)
s0611163's avatar
初始  
s0611163 已提交
967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
        .OrderBy(t => t.Id)
        .ToList();
}
```

## 支持更多数据库

    现有架构实际上支持任何传统关系型数据库

### 如何实现

    以PostgreSQL为例,假如该库尚未支持PostgreSQL

1. 定义一个数据库提供者类,实现IProvider接口

```C#
using LiteSql;
using Npgsql;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;

namespace PostgreSQLTest
{
    public class PostgreSQLProvider : IProvider
    {
        #region OpenQuote 引号
        /// <summary>
        /// 引号
        /// </summary>
        public string OpenQuote
        {
            get
            {
                return "\"";
            }
        }
        #endregion

        #region CloseQuote 引号
        /// <summary>
        /// 引号
        /// </summary>
        public string CloseQuote
        {
            get
            {
                return "\"";
            }
        }
        #endregion

        #region 创建 DbConnection
        public DbConnection CreateConnection(string connectionString)
        {
            return new NpgsqlConnection(connectionString);
        }
        #endregion

        #region 生成 DbParameter
        public DbParameter GetDbParameter(string name, object value)
        {
            return new NpgsqlParameter(name, value);
        }
        #endregion

s0611163's avatar
s0611163 已提交
1035 1036
        #region GetParameterName
        public string GetParameterName(string parameterName, Type parameterType)
s0611163's avatar
初始  
s0611163 已提交
1037
        {
s0611163's avatar
s0611163 已提交
1038
            return "@" + parameterName;
s0611163's avatar
初始  
s0611163 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
        }
        #endregion

        #region 创建获取最大编号SQL
        public string CreateGetMaxIdSql(string key, Type type)
        {
            return string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
        }
        #endregion

        #region 创建分页SQL
        public string CreatePageSql(string sql, string orderby, int pageSize, int currentPage, int totalRows)
        {
            StringBuilder sb = new StringBuilder();
            int startRow = 0;
            int endRow = 0;

            #region 分页查询语句
            startRow = pageSize * (currentPage - 1);

            sb.Append("select * from (");
            sb.Append(sql);
            if (!string.IsNullOrWhiteSpace(orderby))
            {
                sb.Append(" ");
                sb.Append(orderby);
            }
            sb.AppendFormat(" ) row_limit limit {0} offset {1}", pageSize, startRow);
            #endregion

            return sb.ToString();
        }
        #endregion

s0611163's avatar
s0611163 已提交
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
        #region 删除SQL语句模板
        /// <summary>
        /// 删除SQL语句模板 两个值分别对应 “delete from [表名] where [查询条件]”中的“delete from”和“where”
        /// </summary>
        public Tuple<string, string> CreateDeleteSqlTempldate()
        {
            return new Tuple<string, string>("delete from", "where");
        }
        #endregion

        #region 更新SQL语句模板
        /// <summary>
        /// 更新SQL语句模板 三个值分别对应 “update [表名] set [赋值语句] where [查询条件]”中的“update”、“set”和“where”
        /// </summary>
        public Tuple<string, string, string> CreateUpdateSqlTempldate()
        {
            return new Tuple<string, string, string>("update", "set", "where");
        }
        #endregion

s0611163's avatar
初始  
s0611163 已提交
1093 1094 1095
        #region ForContains
        public SqlValue ForContains(string value)
        {
s0611163's avatar
s0611163 已提交
1096
            return new SqlValue("%" + value + "%");
s0611163's avatar
初始  
s0611163 已提交
1097 1098 1099 1100 1101 1102
        }
        #endregion

        #region ForStartsWith
        public SqlValue ForStartsWith(string value)
        {
s0611163's avatar
s0611163 已提交
1103
            return new SqlValue(value + "%");
s0611163's avatar
初始  
s0611163 已提交
1104 1105 1106 1107 1108 1109
        }
        #endregion

        #region ForEndsWith
        public SqlValue ForEndsWith(string value)
        {
s0611163's avatar
s0611163 已提交
1110
            return new SqlValue("%" + value);
s0611163's avatar
初始  
s0611163 已提交
1111 1112 1113 1114 1115 1116
        }
        #endregion

        #region ForDateTime
        public SqlValue ForDateTime(DateTime dateTime)
        {
s0611163's avatar
s0611163 已提交
1117
            return new SqlValue(dateTime);
s0611163's avatar
初始  
s0611163 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
        }
        #endregion

        #region ForList
        public SqlValue ForList(IList list)
        {
            List<string> argList = new List<string>();
            for (int i = 0; i < list.Count; i++)
            {
                argList.Add("@inParam" + i);
            }
            string args = string.Join(",", argList);

            return new SqlValue("(" + args + ")", list);
        }
        #endregion

    }
}
```

如果觉得需要实现的接口太多太麻烦,可以写个不支持lambda表达式的版本,即不实现For开头的接口,如下所示:

```C#
using LiteSql;
using Npgsql;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data.Common;
using System.Text;

namespace PostgreSQLTest
{
    public class PostgreSQLProvider : IProvider
    {
        #region OpenQuote 引号
        /// <summary>
        /// 引号
        /// </summary>
        public string OpenQuote
        {
            get
            {
                return "\"";
            }
        }
        #endregion

        #region CloseQuote 引号
        /// <summary>
        /// 引号
        /// </summary>
        public string CloseQuote
        {
            get
            {
                return "\"";
            }
        }
        #endregion

        #region 创建 DbConnection
        public DbConnection CreateConnection(string connectionString)
        {
            return new NpgsqlConnection(connectionString);
        }
        #endregion

        #region 生成 DbParameter
        public DbParameter GetDbParameter(string name, object value)
        {
            return new NpgsqlParameter(name, value);
        }
        #endregion

s0611163's avatar
s0611163 已提交
1194 1195
        #region GetParameterName
        public string GetParameterName(string parameterName, Type parameterType)
s0611163's avatar
初始  
s0611163 已提交
1196
        {
s0611163's avatar
s0611163 已提交
1197
            return "@" + parameterName;
s0611163's avatar
初始  
s0611163 已提交
1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231
        }
        #endregion

        #region 创建获取最大编号SQL
        public string CreateGetMaxIdSql(string key, Type type)
        {
            return string.Format("SELECT Max({0}) FROM {1}", key, type.Name);
        }
        #endregion

        #region 创建分页SQL
        public string CreatePageSql(string sql, string orderby, int pageSize, int currentPage, int totalRows)
        {
            StringBuilder sb = new StringBuilder();
            int startRow = 0;
            int endRow = 0;

            #region 分页查询语句
            startRow = pageSize * (currentPage - 1);

            sb.Append("select * from (");
            sb.Append(sql);
            if (!string.IsNullOrWhiteSpace(orderby))
            {
                sb.Append(" ");
                sb.Append(orderby);
            }
            sb.AppendFormat(" ) row_limit limit {0} offset {1}", pageSize, startRow);
            #endregion

            return sb.ToString();
        }
        #endregion

s0611163's avatar
s0611163 已提交
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251
        #region 删除SQL语句模板
        /// <summary>
        /// 删除SQL语句模板 两个值分别对应 “delete from [表名] where [查询条件]”中的“delete from”和“where”
        /// </summary>
        public Tuple<string, string> CreateDeleteSqlTempldate()
        {
            return new Tuple<string, string>("delete from", "where");
        }
        #endregion

        #region 更新SQL语句模板
        /// <summary>
        /// 更新SQL语句模板 三个值分别对应 “update [表名] set [赋值语句] where [查询条件]”中的“update”、“set”和“where”
        /// </summary>
        public Tuple<string, string, string> CreateUpdateSqlTempldate()
        {
            return new Tuple<string, string, string>("update", "set", "where");
        }
        #endregion

s0611163's avatar
初始  
s0611163 已提交
1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303
        public SqlValue ForContains(string value)
        {
            throw new NotImplementedException();
        }

        public SqlValue ForStartsWith(string value)
        {
            throw new NotImplementedException();
        }

        public SqlValue ForEndsWith(string value)
        {
            throw new NotImplementedException();
        }

        public SqlValue ForDateTime(DateTime dateTime)
        {
            throw new NotImplementedException();
        }

        public SqlValue ForList(IList list)
        {
            throw new NotImplementedException();
        }

    }
}
```

2. 定义LiteSqlFactory类

    下面代码是.NET 5下的代码

```C#
using LiteSql;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;

namespace PostgreSQLTest
{
    public class LiteSqlFactory
    {
        #region 变量
        private static ILiteSqlClient _liteSqlClient;
        #endregion

        #region 静态构造函数
        static LiteSqlFactory()
        {
            var configurationBuilder = new ConfigurationBuilder().AddJsonFile("config.json");
            var configuration = configurationBuilder.Build();
            string connectionString = configuration.GetConnectionString("DefaultConnection");
s0611163's avatar
优化  
s0611163 已提交
1304
            _liteSqlClient = new LiteSqlClient(connectionString, typeof(PostgreSQLProvider), new PostgreSQLProvider());
s0611163's avatar
初始  
s0611163 已提交
1305 1306 1307 1308 1309 1310 1311
        }
        #endregion

        #region 获取 ISession
        /// <summary>
        /// 获取 ISession
        /// </summary>
s0611163's avatar
s0611163 已提交
1312 1313
        /// <param name="splitTableMapping">分表映射</param>
        public static ISession GetSession(SplitTableMapping splitTableMapping = null)
s0611163's avatar
初始  
s0611163 已提交
1314
        {
s0611163's avatar
s0611163 已提交
1315
            return _liteSqlClient.GetSession(splitTableMapping);
s0611163's avatar
初始  
s0611163 已提交
1316 1317 1318 1319 1320 1321 1322
        }
        #endregion

        #region 获取 ISession (异步)
        /// <summary>
        /// 获取 ISession (异步)
        /// </summary>
s0611163's avatar
s0611163 已提交
1323 1324
        /// <param name="splitTableMapping">分表映射</param>
        public static async Task<ISession> GetSessionAsync(SplitTableMapping splitTableMapping = null)
s0611163's avatar
初始  
s0611163 已提交
1325
        {
s0611163's avatar
s0611163 已提交
1326
            return await _liteSqlClient.GetSessionAsync(splitTableMapping);
s0611163's avatar
初始  
s0611163 已提交
1327 1328 1329 1330 1331 1332 1333 1334
        }
        #endregion

    }
}
```

    然后就可以使用了
s0611163's avatar
s0611163 已提交
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816

### 支持ClickHouse

#### 定义ClickHouseProvider类实现IProvider接口

```C#
using ClickHouse.Client.ADO;
using ClickHouse.Client.ADO.Parameters;
using LiteSql;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiteSql.Provider
{
    public class ClickHouseProvider : IProvider
    {
        #region Quote
        public string OpenQuote
        {
            get
            {
                return "\"";
            }
        }

        public string CloseQuote
        {
            get
            {
                return "\"";
            }
        }
        #endregion

        #region 创建Db对象
        public DbConnection CreateConnection(string connectionString)
        {
            return new ClickHouseConnection(connectionString);
        }

        public DbCommand GetCommand(DbConnection conn)
        {
            DbCommand command = conn.CreateCommand();
            return command;
        }

        public DbCommand GetCommand(string sql, DbConnection conn)
        {
            DbCommand command = conn.CreateCommand();
            command.CommandText = sql;
            return command;
        }

        public DbParameter GetDbParameter(string name, object value)
        {
            DbParameter parameter = new ClickHouseDbParameter();
            parameter.ParameterName = name.Trim(new char[] { '{', '}' }).Split(':')[0];
            parameter.Value = value;
            DbType dbType = ColumnTypeUtil.GetDBType(value);
            parameter.DbType = dbType;
            return parameter;
        }
        #endregion

        #region Create SQL
        public string CreateGetMaxIdSql(string tableName, string key)
        {
            return string.Format("SELECT Max({0}) FROM {1}", key, tableName);
        }

        public string CreatePageSql(string sql, string orderby, int pageSize, int currentPage)
        {
            StringBuilder sb = new StringBuilder();
            int startRow = 0;
            int endRow = 0;

            #region 分页查询语句
            startRow = pageSize * (currentPage - 1);

            sb.Append("select * from (");
            sb.Append(sql);
            if (!string.IsNullOrWhiteSpace(orderby))
            {
                sb.Append(" ");
                sb.Append(orderby);
            }
            sb.AppendFormat(" ) row_limit limit {0},{1}", startRow, pageSize);
            #endregion

            return sb.ToString();
        }
        #endregion

        #region 删除SQL语句模板
        /// <summary>
        /// 删除SQL语句模板 两个值分别对应 “delete from [表名] where [查询条件]”中的“delete from”和“where”
        /// </summary>
        public Tuple<string, string> CreateDeleteSqlTempldate()
        {
            return new Tuple<string, string>("alter table", "delete where");
        }
        #endregion

        #region 更新SQL语句模板
        /// <summary>
        /// 更新SQL语句模板 三个值分别对应 “update [表名] set [赋值语句] where [查询条件]”中的“update”、“set”和“where”
        /// </summary>
        public Tuple<string, string, string> CreateUpdateSqlTempldate()
        {
            return new Tuple<string, string, string>("alter table", "update", "where");
        }
        #endregion

        #region GetParameterName
        public string GetParameterName(string parameterName, Type parameterType)
        {
            return "{" + parameterName + ":" + parameterType.Name + "}";
        }
        #endregion

        #region For Lambda

        public SqlValue ForContains(string value)
        {
            return new SqlValue("%" + value + "%");
        }

        public SqlValue ForStartsWith(string value)
        {
            return new SqlValue(value + "%");
        }

        public SqlValue ForEndsWith(string value)
        {
            return new SqlValue("%" + value);
        }

        public SqlValue ForDateTime(DateTime dateTime)
        {
            return new SqlValue(dateTime);
        }

        public SqlValue ForList(IList list)
        {
            List<string> argList = new List<string>();
            for (int i = 0; i < list.Count; i++)
            {
                argList.Add("@inParam" + i);
            }
            string args = string.Join(",", argList);

            return new SqlValue("(" + args + ")", list);
        }

        #endregion

    }
}
```

#### ColumnTypeUtil工具类

类型转换暂时只写了DateTime和String类型,需要补充

```C#
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiteSql.Provider
{
    public class ColumnTypeUtil
    {
        public static DbType GetDBType(object value)
        {
            Type type = value.GetType();
            if (type == typeof(DateTime))
            {
                return DbType.DateTime;
            }
            else if (type == typeof(string))
            {
                return DbType.String;
            }
            return DbType.String;
        }
    }
}
```

#### 定义LiteSqlFactory

```C#
using LiteSql;
using LiteSql.Provider;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClickHouseTest
{
    public class LiteSqlFactory
    {
        #region 变量
        private static ILiteSqlClient _liteSqlClient;
        #endregion

        #region 静态构造函数
        static LiteSqlFactory()
        {
            var configurationBuilder = new ConfigurationBuilder().AddJsonFile("config.json");
            var configuration = configurationBuilder.Build();
            string connectionString = configuration.GetConnectionString("DefaultConnection");

            _liteSqlClient = new LiteSqlClient(connectionString, typeof(ClickHouseProvider), new ClickHouseProvider());
        }
        #endregion

        #region 获取 ISession
        /// <summary>
        /// 获取 ISession
        /// </summary>
        /// <param name="splitTableMapping">分表映射</param>
        public static ISession GetSession(SplitTableMapping splitTableMapping = null)
        {
            return _liteSqlClient.GetSession(splitTableMapping);
        }
        #endregion

        #region 获取 ISession (异步)
        /// <summary>
        /// 获取 ISession (异步)
        /// </summary>
        /// <param name="splitTableMapping">分表映射</param>
        public static async Task<ISession> GetSessionAsync(SplitTableMapping splitTableMapping = null)
        {
            return await _liteSqlClient.GetSessionAsync(splitTableMapping);
        }
        #endregion

    }
}
```

#### 实体类

```C#
using LiteSql;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Models
{
    [Table("people_face_replica")]
    public class PeopleFace
    {
        [Column("captured_time")]
        public DateTime CapturedTime { get; set; }

        [Key]
        [Column("camera_id")]
        public string CameraId { get; set; }

        [Column("camera_fun_type")]
        public string CameraFunType { get; set; }

        [Key]
        [Column("face_id")]
        public string FaceId { get; set; }

        [Column("extra_info")]
        public string ExtraInfo { get; set; }

        [Column("event")]
        public string Event { get; set; }

        [Column("data_source3")]
        public string DataSource3 { get; set; }

        [Column("panoramic_image_url")]
        public string PanoramicImageUrl { get; set; }

        [Column("portrait_image_url")]
        public string PortraitImageUrl { get; set; }

    }
}
```

#### config.json文件

```json
{
  "ConnectionStrings": {
    "DefaultConnection": "Database=default;Username=default;Password=;Host=192.168.120.130;Port=8123;Compression=False;UseSession=False;Timeout=120;allowMultiQueries=true"
  }
}
```

#### 单元测试代码

```C#
using LiteSql;
using System.Data.Common;
using System.Runtime.InteropServices;
using Models;
using Utils;
using ClickHouse.Client.ADO;
using ClickHouse.Client.ADO.Parameters;
using System.Text;
using Microsoft.Extensions.Configuration;

namespace ClickHouseTest
{
    [TestClass]
    public class QueryTest
    {
        #region 测试查询数量
        [TestMethod]
        public void Test1Count()
        {
            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);

            long count = session.QueryCount("select * from people_face_replica");
            Console.WriteLine("总数=" + count.ToString("# #### #### ####"));
            Assert.IsTrue(count > 0);
        }
        #endregion

        #region 测试查询
        [TestMethod]
        public void Test5Query()
        {
            int queryCount = 10;
            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);

            List<PeopleFace> list = session.CreateSql("select * from people_face_replica t")
                .AppendFormat(" where t.captured_time < toDateTime('{0}')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"))
                .Append(" order by captured_time desc ")
                .Append(" limit " + queryCount)
                .QueryList<PeopleFace>();

            if (list.Count != queryCount)
            {
                Console.WriteLine(list.Count + " / " + queryCount);
            }
            else
            {
                Console.WriteLine("总数=" + list.Count);
            }
            Assert.IsTrue(list.Count == queryCount);

            list.ForEach(item => Console.WriteLine(ModelToStringUtil.ToString(item)));
        }
        #endregion

        #region 测试参数化查询 toDateTime({EndTime:String})
        [TestMethod]
        public void Test5QueryByParam()
        {
            int queryCount = 10;
            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);

            ClickHouseDbParameter[] parameter = new ClickHouseDbParameter[1];
            parameter[0] = new ClickHouseDbParameter();
            parameter[0].ParameterName = "EndTime";
            parameter[0].Value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            StringBuilder sql = new StringBuilder(@"
                select * 
                from people_face_replica t
                where t.captured_time < toDateTime({EndTime:String})
                order by captured_time desc ")
                .AppendFormat(" limit {0}", queryCount);

            List<PeopleFace> list = session.QueryList<PeopleFace>(sql.ToString(), parameter);

            if (list.Count != queryCount)
            {
                Console.WriteLine(list.Count + " / " + queryCount);
            }
            else
            {
                Console.WriteLine("总数=" + list.Count);
            }
            Assert.IsTrue(list.Count == queryCount);

            list.ForEach(item => Console.WriteLine(ModelToStringUtil.ToString(item)));
        }
        #endregion

        #region 测试参数化查询 {EndTime:DateTime}
        [TestMethod]
        public void Test5QueryByParam2()
        {
            int queryCount = 10;
            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);

            ClickHouseDbParameter[] parameter = new ClickHouseDbParameter[1];
            parameter[0] = new ClickHouseDbParameter();
            parameter[0].ParameterName = "EndTime";
            parameter[0].Value = DateTime.Now;

            StringBuilder sql = new StringBuilder(@"
                select * 
                from people_face_replica t
                where t.captured_time < {EndTime:DateTime}
                order by captured_time desc ")
                .AppendFormat(" limit {0}", queryCount);

            List<PeopleFace> list = session.QueryList<PeopleFace>(sql.ToString(), parameter);

            if (list.Count != queryCount)
            {
                Console.WriteLine(list.Count + " / " + queryCount);
            }
            else
            {
                Console.WriteLine("总数=" + list.Count);
            }
            Assert.IsTrue(list.Count == queryCount);

            list.ForEach(item => Console.WriteLine(ModelToStringUtil.ToString(item)));
        }
        #endregion

        #region 测试参数化查询 使用SqlString
        [TestMethod]
        public void Test5QueryByParam3()
        {
            int queryCount = 10;
            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);

            List<PeopleFace> list = session.CreateSql("select * from people_face_replica t")
                .Append("where t.captured_time < @EndTime", new { EndTime = DateTime.Now })
                .Append("order by captured_time desc")
                .AppendFormat("limit {0}", queryCount)
                .QueryList<PeopleFace>();

            if (list.Count != queryCount)
            {
                Console.WriteLine(list.Count + " / " + queryCount);
            }
            else
            {
                Console.WriteLine("总数=" + list.Count);
            }
            Assert.IsTrue(list.Count == queryCount);

            list.ForEach(item => Console.WriteLine(ModelToStringUtil.ToString(item)));
        }
        #endregion

        #region 测试参数化查询 Lambda
        [TestMethod]
        public void Test6QueryByLambda()
        {
            int queryCount = 10;
            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);

s0611163's avatar
s0611163 已提交
1817
            List<PeopleFace> list = session.Queryable<PeopleFace>()
s0611163's avatar
s0611163 已提交
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861
                .Where(t => t.CapturedTime < DateTime.Now)
                .OrderByDescending(t => t.CapturedTime)
                .ToPageList(1, queryCount);

            if (list.Count != queryCount)
            {
                Console.WriteLine(list.Count + " / " + queryCount);
            }
            else
            {
                Console.WriteLine("总数=" + list.Count);
            }
            Assert.IsTrue(list.Count == queryCount);

            list.ForEach(item => Console.WriteLine(ModelToStringUtil.ToString(item)));
        }
        #endregion

        #region 测试插入(原生)
        [TestMethod]
        public void Test2Insert1()
        {
            var configurationBuilder = new ConfigurationBuilder().AddJsonFile("config.json");
            var configuration = configurationBuilder.Build();
            string connectionString = configuration.GetConnectionString("DefaultConnection");

            using ClickHouseConnection conn = new ClickHouseConnection(connectionString);
            conn.Open();
            using ClickHouseCommand command = conn.CreateCommand();
            command.CommandText = @"insert into people_face_replica (captured_time, camera_id, camera_fun_type, face_id, data_source3, panoramic_image_url, portrait_image_url, event) 
                values ({captured_time:DateTime}, {camera_id:String}, {camera_fun_type:String}, {face_id:String}, {data_source3:String}, {panoramic_image_url:String}, {portrait_image_url:String}, {event:String})";

            command.Parameters.Add(new ClickHouseDbParameter() { ParameterName = "captured_time", Value = new System.DateTime(2022, 1, 1) });
            command.Parameters.Add(new ClickHouseDbParameter() { ParameterName = "camera_id", Value = "34010449001190310342" });
            command.Parameters.Add(new ClickHouseDbParameter() { ParameterName = "camera_fun_type", Value = "2" });
            command.Parameters.Add(new ClickHouseDbParameter() { ParameterName = "face_id", Value = "3401044900119031020220826120000000000635567" });
            command.Parameters.Add(new ClickHouseDbParameter() { ParameterName = "event", Value = "UPSERT" });
            command.Parameters.Add(new ClickHouseDbParameter() { ParameterName = "panoramic_image_url", Value = "panoramic_image_url" });
            command.Parameters.Add(new ClickHouseDbParameter() { ParameterName = "portrait_image_url", Value = "portrait_image_url" });
            command.Parameters.Add(new ClickHouseDbParameter() { ParameterName = "data_source3", Value = "" });
            command.ExecuteNonQuery();

            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);
s0611163's avatar
s0611163 已提交
1862
            long count = session.Queryable<PeopleFace>().Where(t => t.CapturedTime >= new DateTime(2022, 1, 1)).Count();
s0611163's avatar
s0611163 已提交
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888
            Console.WriteLine("count=" + count);
            Assert.IsTrue(count > 0);
        }
        #endregion

        #region 测试插入
        [TestMethod]
        public void Test2Insert2()
        {
            var configurationBuilder = new ConfigurationBuilder().AddJsonFile("config.json");
            var configuration = configurationBuilder.Build();
            string connectionString = configuration.GetConnectionString("DefaultConnection");

            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);

            PeopleFace peopleFace = new PeopleFace();
            peopleFace.CapturedTime = new DateTime(2022, 1, 1);
            peopleFace.CameraId = "34010400000000000000";
            peopleFace.FaceId = "340104490011905";
            peopleFace.CameraFunType = "2";
            peopleFace.PanoramicImageUrl = "PanoramicImageUrl";
            peopleFace.PortraitImageUrl = "PortraitImageUrl";
            peopleFace.Event = "UPSERT";
            session.Insert(peopleFace);

s0611163's avatar
s0611163 已提交
1889
            long count = session.Queryable<PeopleFace>().Where(t => t.CapturedTime >= new DateTime(2022, 1, 1)).Count();
s0611163's avatar
s0611163 已提交
1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928
            Console.WriteLine("count=" + count);
            Assert.IsTrue(count > 0);
        }
        #endregion

        #region 测试批量插入
        [TestMethod]
        public void Test3BatchInsert()
        {
            var configurationBuilder = new ConfigurationBuilder().AddJsonFile("config.json");
            var configuration = configurationBuilder.Build();
            string connectionString = configuration.GetConnectionString("DefaultConnection");

            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);

            Random rnd = new Random();
            string pre = rnd.NextInt64(0, 10000000000).ToString();
            DateTime? time = null;
            for (int k = 0; k < 2; k++)
            {
                List<PeopleFace> peopleFaceList = new List<PeopleFace>();
                for (int i = 0; i < 5; i++)
                {
                    PeopleFace peopleFace = new PeopleFace();
                    peopleFace.CapturedTime = DateTime.Now;
                    peopleFace.CameraId = pre + "_" + i;
                    peopleFace.FaceId = "340104490011903" + i;
                    peopleFace.CameraFunType = "2";
                    peopleFace.PanoramicImageUrl = "PanoramicImageUrl";
                    peopleFace.PortraitImageUrl = "PortraitImageUrl";
                    peopleFace.Event = "UPSERT";
                    peopleFaceList.Add(peopleFace);

                    if (time == null) time = peopleFace.CapturedTime;
                }
                session.Insert(peopleFaceList);
            }

s0611163's avatar
s0611163 已提交
1929
            long count = session.Queryable<PeopleFace>().Where(t => t.CapturedTime >= time.Value && t.CameraId.StartsWith(pre)).Count();
s0611163's avatar
s0611163 已提交
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
            Console.WriteLine("count=" + count);
            Assert.IsTrue(count > 0);
        }
        #endregion

        #region 测试修改
        [TestMethod]
        public void Test3Update()
        {
            var configurationBuilder = new ConfigurationBuilder().AddJsonFile("config.json");
            var configuration = configurationBuilder.Build();
            string connectionString = configuration.GetConnectionString("DefaultConnection");

            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);

            PeopleFace old = session.CreateSql("select * from people_face_replica where camera_id=@CameraId", new { CameraId = "34010400000000000000" }).Query<PeopleFace>();

            string newExtraInfo = DateTime.Now.ToString("yyyyMMddHHmmss");
            old.ExtraInfo = newExtraInfo;
            session.Update(old);

            Thread.Sleep(100);

s0611163's avatar
s0611163 已提交
1954
            PeopleFace newPeopleFace = session.Queryable<PeopleFace>().Where(t => t.CameraId == "34010400000000000000").First();
s0611163's avatar
s0611163 已提交
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984

            Console.WriteLine(newExtraInfo);
            Console.WriteLine(newPeopleFace.ExtraInfo);
            Assert.IsTrue(newPeopleFace.ExtraInfo == newExtraInfo);
        }
        #endregion

        #region 测试批量修改
        [TestMethod]
        public void Test4BatchUpdate()
        {
            var configurationBuilder = new ConfigurationBuilder().AddJsonFile("config.json");
            var configuration = configurationBuilder.Build();
            string connectionString = configuration.GetConnectionString("DefaultConnection");

            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);

            List<PeopleFace> oldList = session.CreateSql("select * from people_face_replica where captured_time>@Time", new { Time = DateTime.Now.AddMinutes(-1) }).QueryList<PeopleFace>();

            string newExtraInfo = DateTime.Now.ToString("yyyyMMddHHmmss");
            oldList.ForEach(old =>
            {
                old.ExtraInfo = newExtraInfo;
                session.Update(old);
            });
            //session.Update(oldList); //似乎不支持,错误信息:Multi-statements are not allowed

            Thread.Sleep(100);

s0611163's avatar
s0611163 已提交
1985
            long count = session.Queryable<PeopleFace>().Where(t => t.ExtraInfo == newExtraInfo).Count();
s0611163's avatar
s0611163 已提交
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009

            Console.WriteLine(count + "条已更新");
            Assert.IsTrue(count > 0);
        }
        #endregion

        #region 测试批量修改
        [TestMethod]
        public void Test4BatchUpdate2()
        {
            var configurationBuilder = new ConfigurationBuilder().AddJsonFile("config.json");
            var configuration = configurationBuilder.Build();
            string connectionString = configuration.GetConnectionString("DefaultConnection");

            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);

            string newExtraInfo = DateTime.Now.AddYears(-1).ToString("yyyyMMddHHmmss");

            //可以这样批量更新
            session.CreateSql("alter table people_face_replica update extra_info=@ExtraInfo where 1=1", new { ExtraInfo = newExtraInfo }).Execute();

            Thread.Sleep(100);

s0611163's avatar
s0611163 已提交
2010
            long count = session.Queryable<PeopleFace>().Where(t => t.ExtraInfo == newExtraInfo).Count();
s0611163's avatar
s0611163 已提交
2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026

            Console.WriteLine(count + "条已更新");
            Assert.IsTrue(count > 0);
        }
        #endregion

        #region 删除
        [TestMethod]
        public void Test9Delete()
        {
            var configurationBuilder = new ConfigurationBuilder().AddJsonFile("config.json");
            var configuration = configurationBuilder.Build();
            string connectionString = configuration.GetConnectionString("DefaultConnection");

            using ISession session = LiteSqlFactory.GetSession();
            session.OnExecuting = (s, p) => Console.WriteLine(s);
s0611163's avatar
s0611163 已提交
2027
            long count = session.Queryable<PeopleFace>().Where(t => t.CapturedTime > DateTime.Now.AddMinutes(-1)).Count();
s0611163's avatar
s0611163 已提交
2028 2029 2030 2031 2032 2033
            Console.WriteLine("删除前数量=" + count);

            session.CreateSql("captured_time>@Time", new { Time = DateTime.Now.AddDays(-10) }).DeleteByCondition<PeopleFace>();

            Thread.Sleep(100);

s0611163's avatar
s0611163 已提交
2034
            count = session.Queryable<PeopleFace>().Where(t => t.CapturedTime > DateTime.Now.AddMinutes(-1)).Count();
s0611163's avatar
s0611163 已提交
2035 2036 2037 2038 2039 2040 2041 2042 2043
            Console.WriteLine("删除后数量=" + count);

            Assert.IsTrue(count == 0);
        }
        #endregion

    }
}
```