Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Peta Poco: How to pass multiple parameters to a Fetch<T>

My Code:

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);

This code produces an error:

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

I wish to know what the correct syntax is?

like image 579
Paul Stanley Avatar asked Dec 11 '15 19:12

Paul Stanley


2 Answers

I'm not really familiar with petapoco, but by the error message, it seems to be trying to bind the parameters to the property of the object you pass in to the Fetch call. If so, try something like this instead:

var results = db.Fetch<Person>(sql, new {t1 = t1, t2 = t2});
like image 66
sstan Avatar answered Sep 20 '22 14:09

sstan


The documentation isn't overly direct, but for positional parameters you need to use zero-indexed placeholder names @0, @1... in your query. Try:

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

If you use named placeholders, PetaPoco looks for an object with that property name, hence the error message you're getting. For example:

sql.Append("AND date_created>=@start AND date_created<=@end", 
    new 
        { 
            start=DateTime.UtcNow.AddDays(-2), 
            end=DateTime.UtcNow 
        }
    );
like image 32
Daniel Flint Avatar answered Sep 19 '22 14:09

Daniel Flint