Convention-based projections for queries

Jimmy Bogard posted a very interesting post Autoprojecting LINQ queries. Few months ago, I started an experiment for doing exactly this. My code is here.

My experiment handle the same scenario Jimmy shown but also supports many to one relationships.

Suppose you have a domain class like this:

public class Person
{
  public virtual string Name   { get; set; }
  public virtual Person Parent { get; set; }
  public virtual Country Country { get; set; }
}

and a dto like this:

public class PersonDto
{
  public virtual string Name   { get; set; }
  public virtual string CountryName { get; set; }
  public virtual string ParentName  { get; set; }
  public virtual string ParentCountryName { get; set; }
}

you can automap the projection as follows:

var mapper = new Mapper();
mapper.AddMap<Person, PersonDto>();
var dtos = query<Person>().Select(mapper.GetProjection<Person, PersonDto>());

;

The call to mapper.GetProjection returns the following expression:

This query works very well with nhibernate.

Expression<Func<Person, PersonDto>> projection =
  person => new PersonDto
    {
     Name = person.Name,
     CountryName = person.Country != null ? person.Country.Name : string.Empty   
     ParentName = person.Parent != null ? person.Parent.Name : string.Empty    
     ParentCountryName = person.Parent != null ? (person.Parent.Country != null ? person.Parent.Country.Name : string.Empty) : string.Empty    
    }

The code is very simple and it is opensource. Feel free to enhance it :)


blog comments powered by Disqus
  • Categories

  • Archives