Adding Custom Query in Domain Service Class
On Day 3 we went deep in generated Domain Class. Now we do have an understanding on what all methods are there in the Domain Service Class.
First question we need to ask ourselves is that, “why we need to add custom query in domain service class.
We add custom query in Domain Service class to achieve certain application logic. When to meet certain business requirement we add custom query as application logic in Domain Service Class , that gets available in both presentation layer and middle layer.
Let us go ahead and try to achieve below business task
- Passing parameter to query. Such as we want to fetch a particular person of a given person id.
- Retuning multiple and single results from query
We will see how we could add query methods to the generated Data Context class.
To return a single object, you need to make query iscomposable attribute to false. Any method returning single object should be attributed as below,
To filter out person on a particular PersonID you can use lambda expression as below,
SchoolRIAService.cs
[Query(IsComposable=false)] public Person GetPersonById(int PersonID) { return this.ObjectContext.People.SingleOrDefault(p => p.PersonID == PersonID); }
Above code would fetch you a single person of given person Id. At the presentation layer in Silverlight client you can call above custom query as below,
MainPage.xaml.cs
using System.Windows.Controls; using DemoDay2.Web; using System.ServiceModel.DomainServices.Client; namespace DemoDay2 { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); SchoolRIAContext proxy = new SchoolRIAContext(); LoadOperation<Person> loadPerson = proxy.Load(proxy.GetPersonByIdQuery(1)); grdRIADataGrid.ItemsSource = loadPerson.Entities ; } } }
If you want to add custom query as of your requirement returning multiple entities, you can add a method in Domain Service Class.
SchoolRIAService.cs
</span> <pre> public IQueryable<Person> GetPersonByStartName(string startchar) { return this.ObjectContext.People.Where(s => s.FirstName.StartsWith(startchar)); }
Above method will return all the people with given start name. At the presentation layer in Silverlight client you can call above custom query as below,
MainPage.xaml.cs
using System.Windows.Controls; using DemoDay2.Web; using System.ServiceModel.DomainServices.Client; namespace DemoDay2 { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); SchoolRIAContext proxy = new SchoolRIAContext(); LoadOperation<Person> loadPerson = proxy.Load(proxy.GetPersonByStartNameQuery("d")); grdRIADataGrid.ItemsSource = loadPerson.Entities ; } } }
Today we saw how we could add custom query to Domain Service Class matching our business requirement. We can add any application logic in Domain Service Class to be shared in between presentation layer and middle layer.
See you on day 5
Leave a Reply