Question

I want to get counts for various groupings of data in some of my tables and am not sure if it is possible using DAL2.

I want perform queries such as:

SELECT  DISTINCT productType, COUNT(*) FROM Products GROUP BY productType

The information I come across only includes examples that allow the user to specify the WHERE part of the SQL. This example unfortunately skirts right around the WHERE part of the query so I am not sure how I should approach this using DAL2. Is it possible using DAL2 or do I need to query the database another way? If it can be done using DAL2, how do I execute such a query?

Was it helpful?

Solution

The examples showing only the WHERE part mean that PetaPoco fills in the "SELECT * FROM TableName" part for you, but of course you can execute your own sql statement

In your case:

public class ProductCount {
   public int ProductType {get; set;}
   public int Count {get; set;}
}

var ProductCountList = db.Fetch<ProductCount>(@"SELECT DISTINCT productType, 
        COUNT(*) as Count 
        FROM Products 
        GROUP BY productType");

OTHER TIPS

I can't tell you what is best practice. But I have a SQL server back end and use dal2 with a dnn module. I just created a view in SQL server with my grouping and joins and then mapped that view like a table (use view name instead of table name in the class annotations) with an auto increment of false. Worked for me and I get the benefit of precompiled and non dynamic queries. If you need to generate this dynamically, I am not sure what the best approach is.

I would love to hear from other members about this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top