参数化 ServiceStack 自定义 SQL 查询

Parameterizing a ServiceStack custom SQL query

我有以下自定义 SQL 使用 OrmLite 查询:

var results = db.Select<Tuple<Customer,Purchase>>(@"SELECT c.*, 0 EOT, p1.*
    FROM customer c
    JOIN purchase p1 ON (c.id = p1.customer_id)
    LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND 
        (p1.date < p2.date OR p1.date = p2.date AND p1.id < p2.id))
    WHERE p2.id IS NULL;");

添加可选 WHERE 子句的最佳方法是什么,例如,在字段有值时过滤给定的客户名称字段或向查询添加分页?

如果您正在使用自定义 SQL,您只需要自己构建额外的查询,例如:

var sql = @"SELECT c.*, 0 EOT, p1.*
    FROM customer c
    JOIN purchase p1 ON (c.id = p1.customer_id)
    LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND 
        (p1.date < p2.date OR p1.date = p2.date AND p1.id < p2.id))
    WHERE p2.id IS NULL";

//string name = "Customer Name";
string name = null;
if (name != null)
{
    sql += "\nAND name = @name";
}

int? limit = 100;
if (limit != null)
{
    sql += $"\nLIMIT {limit}";
}

var results = db.Select<Tuple<Customer,Purchase>>(sql, new { name });

一个Live Example of this is available on Gistlyn.