数据元素数量未知的Dapper.net

时间:2017-06-28 08:59:39

标签: arrays dapper

我尝试做的事情是有一个像这样填充的过滤器对象

var filter = new Filter
{
    ThingID = 1,
    Keywords = new[] { "op", "s" }
};

然后能够像这样构建查询:

var sb = new StringBuilder();
sb.AppendLine("select * from Stuff where 1=1");
if (filter.ThingID.HasValue)
{
    sb.AppendLine(" and ThingID = @ThingID");
}
if (filter.Keywords != null)
{
    for (int i = 0; i < filter.Keywords.Length; i++)
    {
        string keyword = filter.Keywords[i];
        if (!string.IsNullOrWhiteSpace(keyword))
        {
            sb.AppendLine(" and ( Model like '%' || @Keywords" + i + " || '%' )");
        }
    }
}
var sql = sb.ToString();
var results = Query<Stuff>(sql, filter).ToList();

如果仅填充ThingID道具,这可以正常工作,但据我所知,Dapper不会以任何方式将关键字作为参数提供。这可能与Dapper有关,还是仅适用于&#34;其中关键字在@ Keywords&#34;?

1 个答案:

答案 0 :(得分:2)

参数需要按名称匹配;您正在添加 Looks andoid:layout_width is set to match_parent in the first case and in the second it is wrap_content. If it is wrap_content, according to the text, the button size shrinks. Moreover first one is inside linearlayout and the second one is outside and whether is it in any layout like Relativelayout? Attributes are different from each layout May be you keep both under same linearlayout and give a try by modifying only the text alone. Hope that helps!!! 之类的参数,但没有@Keywords17属性可供添加。它不会将其解释为Keywords17,如果这是你的意思。 平面阵列的一些自动扩展,但是它用于扩展Keywords[17](尽管扩展本身并不特定于in @Keywords)。目前没有任何东西可以自动帮助你;我建议改为in

DynamicPaameters

请注意这里最后的两个更改 - var args = new DynamicParameters(); args.Add("ThingID", 1); ... if (!string.IsNullOrWhiteSpace(keyword)) { sb.AppendLine(" and ( Model like '%' || @Keywords" + i + " || '%' )"); args.Add("Keywords" + i, keyword); } ... var cmd = new CommandDefinition(sql, args, flags: CommandFlags.NoCache); var results = Query<Stuff>(cmd).AsList(); 将有助于避免为类似但不同的SQL构建大量查找条目(尽管您可能会选择支付此项以减少每个项目的费用,由您决定) 。 CommandFlags.NoCache代替AsList可以避免额外的列表分配。