WCF RIA servies has great support for Linq and Entity Framework. But if you have a large domain model and would like to send a slightly different view of the entities (for example merge some normalised entities into one conceptual entity, or only send a subset of fields, or only send a selection of the children in a parent-child collection) then DTOs may be what you are after.
DTO stands for Data Transfer Object and is simply a view of the entity that is what you really want to send to the silverlight client, not what the database is storing or the rest of your application is using. The best bit about these is RIA services will automagically add support for INotifyPropertyChanged, validation and change tracking!
You can create these DTOs just as any other class as they are POCOs (Plan old CLR Objects) and we will have full control over what is sent to the client and Data Annotations for validation or even custom methods for the entity.
Create a class to represent your entity using public properties as the attributes. Mark the key of the entity with the DataAnnotations.Key attribute as shown below. Associations can also be mapped as shown below.
using System.ComponentModel.DataAnnotations; using System.ServiceModel.DomainServices.Server; public class OrderDTO { [Key] public int OrderID { get; set; } public string Title { get; set; } [Include] [Association("Order_Items", "OrderID", "ItemID", IsForeignKey=false)] public IEnumerable<ItemDTO> Items { get; set; } }
To serve these to silverlight simple create a DomainContext (not a LinqToEntitiesDomainService) and create a method which will act as the GET method.
Another great plus is you can easily filter the child collections that are to be returned to silverlight.
[EnableClientAccess()] public class OrdersDomainService : DomainService { public IEnumerable<OrderDTO> GetOrdersAndItems() { return context.Orders.Select(p => new OrderDTO { //TODO map the order details Items = p.Items .Where(m => m.Cost > 100.0) // easily filter nested collection .Select(m => new ItemDTO { // TODO map the item details } }; } // You may need this for ria to project to silverlight what a ItemDTO actually is. public IEnumerable<ItemDTO> GetItems() { return null; } }
Now on the client side we can use these entities just as if the LinqToEntitiesDomainService projected them from the Entity Framework.
I hear more support is coming to RIA for these POCO entities so stay tuned!