private static readonly Regex pseudoRegex = new Regex(@"\$([\p{L}_][\p{L}\p{N}_]*)\$", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);
public static string ReplacePseudoParameter(IDbConnection conn, string cmdText)
{
return pseudoRegex.Replace(cmdText, match => {
var key = match.Groups[1].Value;
if (conn is OleDbConnection)
{
return "?" + key + "?";
}
return (conn is OracleConnection ? ":" : "@") + key;
});
}
使用方式是在参数名称两边加上$
:
string sqlCommandText = @"SELECT * FROM USERS WHERE ID=$ID$";
Users user = conn.Query<Users>(ReplacePseudoParameter(conn, sqlCommandText), new { ID = 2 }).FirstOrDefault();