I am working on a project where we need to create complex queries against a WCF service.
The service uses linq to sql at the backend and projects queries to data transfe
If you have long complicated entities then creating a projection by hand is a nightmare. Automapper
doesn't work because LINQ cannot use it in conjunction with IQueryable.
This here is the perfect solution : Stop using AutoMapper in your Data Access Code
It will generate a projection 'magically' for you and enable you to run an oData query based on your DTO (data transfer object) class.
[Queryable]
public IQueryable<DatabaseProductDTO> GetDatabaseProductDTO(ODataQueryOptions<DatabaseProductDTO> options)
{
// _db.DatabaseProducts is an EF table
// DatabaseProductDTO is my DTO object
var projectedDTOs = _db.DatabaseProducts.Project().To<DatabaseProductDTO>();
var settings = new ODataQuerySettings();
var results = (IQueryable<DatabaseProductDTO>) options.ApplyTo(projectedDTOs, settings);
return results.ToArray().AsQueryable();
}
I run this with
/odata/DatabaseProductDTO?$filter=FreeShipping eq true
Note: this article is from a couple years ago and it's possible that by now AutoMapper
has functionality like this built in. I just don't have time I check this myself right now. The inspiration for the above referenced article was based on this article by the author of AutoMapper itself - so it's possible some improved version of it is now included. The general concept seems great and this version is working well for me.
I believe that you can return DTO's by using OData services.
Take a look at http://www.codeproject.com/Articles/135490/Advanced-using-OData-in-NET-WCF-Data-Services. Particularly the 'Exposing a transformation of your database' section. You can flatten your entity objects into a DTO and have the client run queries against this DTO model.
Is that something you are looking for?
With OData
services, you are not bound to return database entities directly. You can simply return any DTO
in queryable format. Then with the help of LINQ's Select()
method, you can simply convert any database entity into DTO
just before serving the query:
public class DataModel
{
public DataModel()
{
using (var dbContext = new DatabaseContext())
{
Employees = from e in dbContext.Employee
select new EmployeeDto
{
ID = e.EmployeeID,
DepartmentID = e.DepartmentID,
AddressID = e.AddressID,
FirstName = e.FirstName,
LastName = e.LastName,
StreetNumber = e.Address.StreetNumber,
StreetName = e.Address.StreetName
};
}
}
/// <summary>Returns the list of employees.</summary>
public IQueryable<EmployeeDto> Employees { get; private set; }
}
You can now easily set this up as a OData service like this:
public class EmployeeDataService : DataService<DataModel>
For full implementation details, see this excellent article on the subject. OData services are actually very very powerful once you get the hand of them.