4. Query Classes

In this tutorial, you will create a query service and learn about query service conventions.

To complete this tutorial download previous solution from here or jump to previous tutorial.

Create a Query Service

Now you will create a query service to see all the tasks completed. Add below code to Tasks class in Task.cs.

... public class Tasks : Query<Task> { ... public List<Task> ByCompleted(bool completed) { return By(t => t.Completed == completed); } }

By method comes from Query<T> base class, and it simply accepts a lambda expression with one parameter of type T. For this example By method will accept a parameter of type Task.

Like every public method, this query method is also exposed as a business service. Build and run AppHost.Service to see your completed tasks.

When a query method returns a list of objects, the convention is to name the method as By. When a query method takes only one parameter, in order to prevent confusion it is recommended to include name of the only parameter in the method name. This is why this method is named as ByCompleted. For more information see: Queries

Testing Queries

Now add following test case to your TaskTest class;

[TestFixture] public class TaskTest : TestBase { ... [Test] public void Tasks_ByCompleted__filters_tasks_by_completed_column() { var taskManager = Context.Get<TaskManager>(); taskManager.CreateTask("incomplete"); taskManager.CreateTask("completed 1").Complete(); taskManager.CreateTask("completed 2").Complete(); BeginTest(); var actual = Context.Query<Tasks>().ByCompleted(true); Assert.AreEqual(2, actual.Count); Assert.AreEqual("completed 1", actual[0].Name); Assert.AreEqual("completed 2", actual[1].Name); } }

Note that there is a Context.Query<T>() shortcut to access query classes. Unlike Context.Get<T>() this shortcut is available in module projects as well, so that you don't have to inject query classes.


Query classes helps you to organize your query methods for the same table into one class, so that you can create reusable query methods.

Now try to create other query methods that accepts more than one parameter, re-run and see the results.

Once you are ready, you can proceed to next page to learn how to create service packages and expose your business services publicly.

You can download complete source code for this tutorial here