Dapper.NET 值内联

示例

有时,参数的便利性(就维护和表达能力而言)可能会被其将其视为参数的性能成本所抵消。例如,当页面大小由配置设置固定时。或者状态值与值匹配enum。考虑:

var orders = connection.Query<Order>(@"
select top (@count) * -- these brackets are an oddity of SQL Server
from Orders
where CustomerId = @customerId
and Status = @open", new { customerId, count = PageSize, open =OrderStatus.Open});

这里唯一的真实参数是customerId-其他两个是实际上不会更改的伪参数。如果RDBMS将其检测为常量,通常可以做得更好。Dapper为此有一种特殊的语法-{=name}而不是@name-适用于数字类型。(这可以最大程度地减少来自SQL注入的攻击面)。示例如下:

var orders = connection.Query<Order>(@"
select top {=count} *
from Orders
where CustomerId = @customerId
and Status = {=open}", new { customerId, count = PageSize, open =OrderStatus.Open});

Dapper在发出SQL之前用文字替换值,因此RDBMS实际上会看到以下内容:

select top 10 *
from Orders
where CustomerId = @customerId
and Status = 3

当允许RDBMS系统不仅做出更好的决策,而且开放实际参数阻止的查询计划时,这特别有用。例如,如果列谓词与参数相对,则无法使用该列上具有特定值的过滤索引。这是因为下一个查询可能具有除那些指定值之一之外的参数。

使用文字值,查询优化器能够使用过滤后的索引,因为它知道该值在将来的查询中无法更改。