Dto generator and repository integration

I have a project where I use repository pattern, interface code access domain object through a service, and the service return Dto. One of the bad side of the dto is that they are boring to write and to maintain. The main risk is that developers does this error

Mmmm I had to show a combo with all the typologies of the current customer, let me seee, I have already a service that return Typlogy object given the customer Id, ok I’ll use it. Can you spot the error???

The error is that the Typology object can contain (and in my situation is true) a lot of properties, some of them are long string, so the developer is retrieving a lot of unnecessary data from the service. The obvious solution is Dto, but noone wants to write them, so it is time to use code generation. With a T4 template I’m able to write stuff like this.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    template = new DtoFactoryTemplate (  
        @"..\..\..\..\Common\Model\MyProject.Analyzer.Entities.Dll", 
        Path.GetDirectoryName(Host.TemplateFile),
        "MyProject.Entities.Analysis.Typology",
        "TypologyLinkDto",
        "MyProject.Service.Dto",
        "http://www.nablasoft.com",
        1, 
        new String[] {"Id", "Name", "CustomerId"},
        null,
        true, true, true);     
    template.RenderToFile(@"..\Dto\Generated\TypologyLinkDto.cs"); 

Ok it still needs to be cleaned a little, because a lot of the parameter are optional but it does the work, it generates this object.

image

It is a good DTO with the three property names I requested, now with Linq2Nhibernate and repository pattern I can write this service method.

1
2
3
4
5
6
public List<TypologyLinkDto> GetTipologiesLinkForCustomer(Int32 customerId)
{
    return Repository.Typology.Query(
        t => t.CustomerId == customerId,
        TypologyLinkDto.Assembler.ExpressionSelector);
}

Thanks to autogenerated code I can use autogenerated Assembler.ExpressionSelector that can be passed as a selector function, resulting query is.

1
exec sp_executesql N'SELECT this_.kety_id as y0_, this_.kety_clieId as y1_, this_.kety_name as y2_ FROM KeyTypology this_ WHERE this_.kety_clieId = @p0',N'@p0 int',@p0=1

This permits to speed up the application because now I retrieve only the data I needed from the database and nothing more, and the good part is that dto is autogenerated, so I can write this code in almost 20 seconds.

alk.

Tags: Code Generation