Search code examples
c#sqlwcflinqdto

Query DTO objects through WCF with linq to sql backend


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 transfer objects like this:


    dbContext.GetQueryable()
                  .Where(x => x.Id == formatId)
                    .Select(x => FormatHelper.PopulateMSFormat(x))
                    .ToList();

What I want to do is to specify a query on the client side, lets say i want to query all formats having a certain property or a couple of them. Something in the style of this:


     var assets = client.QueryForAssets().Where(x => (x.name == "Test" || x == "Arne") && x.doe ==  "john");

Iam aware that I can't return IQueryable over WCF but that something like that can be done with OData services. The problem is that I have to return the DTO's and OData let me quite easily bind to L2S-datacontext which exposes my data model and not the DTO's.

So is there a good way of serializing a query against the DTO that efficiently will propagate to the l2s layer?

I thought about writing my own query language, but I found out that it would be quite hard to build the correct expression tree as a predicate to l2s as there is no mapping from the DTO to the linq classes.


Solution

  • 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.