Search code examples
sql-serverrazorasp.net-webpages

If equals or greather than 3 rows


I'm trying to make a review section, but I only want it to show if there's 3 or more reviews posted.

When I do this I just seem to get an error.

@{
  var reviewCount = db.Query("SELECT COUNT(DISTINCT ID) FROM Reviews");
}

@if (reviewCount >= 3)
{
    <section class="col-md-12 reviews">
        <h2>Anmeldelser</h2>
        @foreach (var row in db.Query("SELECT TOP 3 * FROM Reviews ORDER BY DateTime"))
        {
            <article class="col-md-4">
                <p>" @row.Text "</p> <p>- @row.FirstName @row.LastName</p>
            </article>
        }
    </section>
}

Solution

  • If you just want a single value returned from your database operation, you should use the QueryValue method instead of Query. The first returns a scalar value whereas the second returns a collection of DynamicRecord objects.

    @{
      var reviewCount = db.QueryValue("SELECT COUNT(DISTINCT ID) FROM Reviews");
    }
    
    @if (reviewCount >= 3){
        ...