Question

I'm using the brilliant PetaPoco as my ORM for a small WCF service. I have a small method that gets 5 random records from SQL:

public IEnumerable<Stock> GetRandomStock(int number)
{
        Database db = new Database("MyCS");
        var sql = Sql.Builder.Append("SELECT TOP @0 * FROM Stock ORDER BY NEWID()", number);
        var results = db.Query<Stock>(sql);

        return results;
}

If I run the query in Management Studio, I get the correct number of results based on my parameter. when debugging, I can also see that my parameter is being passed to the query.

Any ideas why I don't get any results?

Thanks in advance.

Was it helpful?

Solution

Are you iterating over the results? If not then the query will not run.

You should use Fetch instead Query as Query runs the query only when you start iterating over the results.

public IEnumerable<Stock> GetRandomStock(int number)
{
        Database db = new Database("MyCS");
        var sql = "SELECT TOP @0 * FROM Stock ORDER BY NEWID()";
        var results = db.Fetch<Stock>(sql, number);

        return results;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top