伪位置参数(对于不支持命名参数的提供者)

一些 ADO.NET 提供程序(最值得注意的是:OleDB)不支持命名参数; 而是仅通过位置指定参数,使用 ? 占位符。Dapper 不会知道使用哪个成员,所以 dapper 允许使用替代语法,?foo?; 这与其他 SQL 变体中的 @foo:foo 相同,只是 dapper 会在执行查询之前用 ? 完全替换参数标记。

这与列表扩展等其他功能结合使用,因此以下内容有效:

string region = "North";
int[] users = ...
var docs = conn.Query<Document>(@"
     select * from Documents
     where Region = ?region?
     and OwnerId in ?users?", new { region, users }).AsList();

相应地使用了 .region.users 成员,并且发布了 SQL(例如,有 3 个用户):

     select * from Documents
     where Region = ?
     and OwnerId in (?,?,?)

但是请注意,这短小精悍不会允许同样的参数,使用此功能时,可以多次使用; 这是为了防止必须多次添加相同的参数值(可能很大)。如果需要多次引用相同的值,请考虑声明变量,例如:

declare @id int = ?id?; // now we can use @id multiple times in the SQL

如果变量不可用,则可以在参数中使用重复的成员名称 - 这也会使值明显发送多次:

int id = 42;
connection.Execute("... where ParentId = $id0$ ... SomethingElse = $id1$ ...",
      new { id0 = id, id1 = id });