Code Elegance

DTO and LINQ

I would like to say a little thing about DTO.

With the advent of LINQ most of the things that I wrote in my old post are not necessary anymore. With the new C# 3.0 is not necessary to build a custom new class for every DTO, you can use the capability called Anonymous Type to create new types on the fly.

Take as example the (usual) case of Customer Address objects, and as the lasts post we want to show on a table the list of Customers with their FullAddress.

With LINQ is not necessary to write a new CustomerDTO class, you can use the following code to obtain the same result:

public IEnumerable GetCustomers() { IList<Customer> customers = LoadCustomerFromDB(); IEnumerable list = from c in customers select new { Name=c.Name, FullAddress=(c.Address.Street + + c.Address.City) }; return list; }

This snippet create a new Anonymous Type with two properties (Name and FullAddress) without the need to create a custom class.

Posted in Emanuele DelBono | 2 comments

2 Comments so far

  1. PeteGoo December 5th, 2007 21:30

    The only problem I see is that an Anonymous type will not be compatible with WCF or any service contract. Does this not make it pretty useless as a Data Transfer Object?

  2. blogema December 6th, 2007 12:53

    Hi PeteGoo
    I agree with you. ;-)
    I use the above approach only on windows forms (o web) applications, to pass data to the UI and get it back without pollute the Domain Model with UI Properties.

    Like you said it does not fit in WCF application.

Leave a reply

Spam Protection by WP-SpamFree