一個簡單的方法(如空白的標準值總是可以忽略不計,這是常見的,當這些值從UI形式發起的情況下它只會工作)將始終通過所有三個參數但要構造一個跳過空值的WHERE子句 - 例如。
:
select ID, UserName, Screen, Url, LogAction
from LogTable
Where (@UserName = '' or UserName = @UserName)
and (@Screen = '' or Screen = @Screen)
and (@LogAction = '' or LogAction = @LogAction)
,那麼你會如果你包裹這個了可選參數,如該方法中通過所有三個值,而不管他們是否是空/空或不
return conn.Query<Result>(
@"
select ID, UserName, Screen, Url, LogAction
from LogTable
Where (@UserName = '' or UserName = @UserName)
and (@Screen = '' or Screen = @Screen)
and (@LogAction = '' or LogAction = @LogAction)
",
new
{
UserName = userName?? "",
Screen = screen ?? "",
LogAction = logAction ?? ""
}
);
private IEnumerable<Result> GetData(
string userName = null,
string screen = null,
string logAction = null)
{
using (var conn = GetConnection())
{
return conn.Query<Result>(
@"
select ID, UserName, Screen, Url, LogAction
from LogTable
Where (@UserName = '' or UserName = @UserName)
and (@Screen = '' or Screen = @Screen)
and (@LogAction = '' or LogAction = @LogAction)
",
new
{
UserName = userName ?? "",
Screen = screen ?? "",
LogAction = logAction ?? ""
}
);
}
}
然後,你可以使調用代碼看起來很自然的不同數量的參數 - 例如。
var joeData = GetData(userName: "Joe");
var joeEditData = GetData(userName: "Joe", screen: "save");
然而,如果你的請求總是有三個值(用戶名,屏幕和logAction)只想和你要那麼忽略空/空值就可以了,當然,只需撥打
var data = GetData(request.UserName, request.Screen, request.LogAction);
你在用什麼小巧的插件?據我所知Dapper沒有包含增刪改查方法 –
我已經在這個問題上做了修正。它有幫助嗎? @AlexKrupka –
「查詢語句」是什麼樣的? – christiandev