【问题标题】:Peta Poco: How to pass multiple parameters to a Fetch<T>Peta Poco:如何将多个参数传递给 Fetch<T>
【发布时间】:2016-03-17 20:10:00
【问题描述】:

我的代码:

string sql = "SELECT * FROM people where birthday >= @t1 AND birthday <= @t2"
DateTime t1 = DateTime.Parse("01-01-2000");
DateTime t2 = DateTime.Parse("01-01-2001");
var results = db.Fetch<Person>(sql, t1,t2);

此代码产生错误:

additional information: Parameter '@t1' specified but none of the passed arguments  have a property with this name (in 'SELECT......

我想知道正确的语法是什么?

【问题讨论】:

    标签: c# .net-4.5 petapoco


    【解决方案1】:

    我对 petapoco 不是很熟悉,但根据错误消息,它似乎正在尝试将参数绑定到您传递给 Fetch 调用的对象的 property。如果是这样,请尝试以下方法:

    var results = db.Fetch<Person>(sql, new {t1 = t1, t2 = t2});
    

    【讨论】:

    • 短版:var results = db.Fetch&lt;Person&gt;(sql, new {t1, t2});
    • @Eduardo:嘿,谢谢。不知道您可以这样推断属性名称。
    【解决方案2】:

    documentation 并不过分直接,但对于位置参数,您需要在查询中使用零索引占位符名称@0@1...。试试:

    string sql = "SELECT * FROM people where birthday >= @0 AND birthday <= @1"
    

    如果您使用命名占位符,PetaPoco 会查找具有该属性名称的对象,因此您会收到错误消息。例如:

    sql.Append("AND date_created>=@start AND date_created<=@end", 
        new 
            { 
                start=DateTime.UtcNow.AddDays(-2), 
                end=DateTime.UtcNow 
            }
        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-07
      • 1970-01-01
      • 2018-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多