我正在使用Dapper.NET
开发采购订单搜索功能。用户可以按发票号和购买日期进行搜索。
如果用户在文本框中填写发票号,则按发票号码搜索,
如果用户填写发票号和购买日期,则按发票号和购买日期进行搜索,并且
如果用户填写购买日期,它将按购买日期搜索
所以,查询:
string query = "SELECT PurchaseDate, InvoiceNo, Supplier, Total FROM PurchaseOrder WHERE 1 = 1";
if (!string.IsNullOrEmpty(purchaseOrder.InvoiceNo))
{
query += " AND InvoiceNo = @InvoiceNo";
}
if (purchaseOrder.PurchaseDate != DateTime.MinValue)
{
query += " AND PurchaseDate = @PurchaseDate";
}
return this._db.Query<PurchaseOrder>(sql, ?).ToList();
问题是我不知道如何根据查询中的条件数动态传递值。
答案 0 :(得分:3)
简单的选择:包括所有的东西! Dapper将检查查询并确定哪些显然不需要,并删除它们 - 只发送它在查询中提到的参数。因此,如果某些查询需要@foo
,有些需要@bar
,有些需要两者,有些则不需要,那么只需:{/ p>
int foo = ...
string bar = ...
...Query<ResultType>(sql, new { foo, bar })...
或者手动执行:查看DynamicParameters
。
答案 1 :(得分:1)
从中提取样本 https://github.com/StackExchange/dapper-dot-net
string query = "SELECT PurchaseDate, InvoiceNo, Supplier, Total FROM PurchaseOrder WHERE 1 = 1";
if (!string.IsNullOrEmpty(purchaseOrder.InvoiceNo))
{
sql += " AND InvoiceNo = @InvoiceNo";
}
if (purchaseOrder.PurchaseDate != DateTime.MinValue)
{
sql += " AND PurchaseDate = @PurchaseDate";
}
return this._db.Query<PurchaseOrder>(sql, new {InvoiceNo = new DbString { Value = YourInvoiceNoVariable, IsFixedLength = true, Length = 10, IsAnsi = true });
对于购买日期,您需要决定是将两个参数都包含在一个sql语句中,还是为每个
答案 2 :(得分:0)
您可以将参数提取到类
中 public class Filter
{
public string InvoiceNo { get; set; }
public DateTime PurchaseDate { get; set; }
}
因此,请将过滤器作为参数
发送public IEnumerable<PurchaseOrder> Find(Filter filter)
{
string query = "SELECT PurchaseDate, InvoiceNo, Supplier, Total FROM PurchaseOrder WHERE 1 = 1";
if (!string.IsNullOrEmpty(purchaseOrder.InvoiceNo))
{
query += " AND InvoiceNo = @InvoiceNo";
}
if (purchaseOrder.PurchaseDate != DateTime.MinValue)
{
query += " AND PurchaseDate = @PurchaseDate";
}
return this._db.Query<PurchaseOrder>(sql, filter);
}