-
Notifications
You must be signed in to change notification settings - Fork 2
08 DTO
In the previous workshop you saw how to create server services method callable from the client.
The methods you wrote return an entity.
But sometimes, we don't want an entity but a special class.
In this case, we generally use DTO.
However, IMHO, for good practices, DTO should not be dependent on your communication technology.
So you should not have to add the DataContract / DataMember attributes need by WCF.
In addition of the Spevifications folder, WAQS also created a DTO folder on the generation process.
In this folder, you will create your DTO classes.
For example, imagine that we want to get the last order id, employee id, full name, date and the total.
So in the DTO folder, add this class:
public class LastOderDTO
{
public int OrderId { get; set; }
public int EmployeeId { get; set; }
public string EmployeeFullName { get; set; }
public DateTime Date { get; set; }
public double Total { get; set; }
}
Then, in OrderSpecifications.cs add this method:
public static LastOderDTO GetLastOrder(INorthwindService context)
{
return (from o in context.Orders
where o.EmployeeId.HasValue
orderby o.OrderDate descending
select new LastOderDTO
{
OrderId = o.Id,
EmployeeId = o.EmployeeId.Value,
EmployeeFullName = o.Employee.GetFullName(),
Date = o.OrderDate,
Total = o.GetTotal()
}).FirstOrDefault();
}
Then, after running WAQS / Update Solution Generated Code, you can use it in the client side.
In MainWindowViewModel, add this code
private async Task LoadLastOrderAsync()
{
LastOrder = await _context.GetLastOrderAsync();
}
private LastOrderDTO _lastOrder;
public LastOrderDTO LastOrder
{
get { return _lastOrder; }
private set
{
_lastOrder = value;
NotifyPropertyChanged.RaisePropertyChanged(nameof(LastOrder));
}
}
Load the last order in the RefreshAsync method
await LoadLastOrderAsync();
And also load it on constructor
LoadLastOrderAsync().ConfigureAwait(true);
Now update your MainWindow.xaml like this
And here you go. You now call the GetLastOrder method running in the server and returning a DTO.
As usual, you can download the code here.