C# – Linq-to-SQL and WCF service – data transfer objects

cdtolinq-to-sqlwcf

I'm curious about best practice when developing n-tier application with Linq-to-SQL and WCF service.

In particular, I'm interested, for example, how to return to presentation tier data from two related tables. Suppose next situation (much simplified):

Database has tables:

  • Orders (id, OrderName)
  • OrderDetails (id, orderid, DetailName)

Middle tier has CRUD methods for OrderDetails. So, I need to have way to rebuild entity for attaching to the context for update or insert when it come back from presentation layer.

In presentation layer I need to display list of OrderDetails with corresponding OrderName from the parent table.

There are two approach for classes, that returned from the service:

  1. Use DTO custom class that will encapsulate data from both tables and projection:

    class OrderDetailDTO
    {
      public int Id { get; set; }
      public string DetailName { get; set; }
      public string OrderName { get; set; }
    }
    IEnumerable<OrderDetailDTO> GetOrderDetails()
    {
      var db = new LinqDataContext();
      return (from od in db.OrderDetails
              select new OrderDetailDTO
              {
                Id = od.id,
                DetailName = od.DetailName,
                OrderName = od.Order.OrderName
              }).ToList();
    }
    

    Cons: need to assign every field which is important for presentation layer in both ways (when returning data and when creating new entity for attaching to context, when data comes back from presentation layer)

  2. Use customized Linq-to-SQL entity partial class:

    partial class OrderDetail
    {
      [DataMember]
      public string OrderName
      {
        get
        {
          return this.Order.OrderName    // return value from related entity
        }
        set {}
      }
    }
    
    IEnumerable<OrderDetail> GetOrderDetails()
    {
      var db = new LinqDataContext();
      var loadOptions = new DataLoadOptions();
      loadOptions.LoadWith<OrderDetail>(item => item.Order);
      db.LoadOptions = options;
      return (from od in db.OrderDetails
              select od).ToList();
    }
    

Cons: database query will include all columns from Orders table, Linq-to-SQL will materialize whole Order entity, although I need only one field from it.

Sorry for such long story. May be I missed something? Will appreciate any suggestions.

Best Answer

I would say use DTO and Automapper, not a good idea to expose DB entity as datacontract