see on GitHub

What are transformers?

The easiest explanation of Transformers is that they are LINQ-based server-side projection functions with the ability to load external documents, including additional results, and even to make decisions based on passed parameters, and much more.

Transformers and the session

Because you are working with projections, and not directly with documents, they are not tracked by the session and won't be saved in the database if you call SaveChanges.

Basic example

If we want to transform our query or load results, we need to perform the following steps:

  • first we need to create a transformer. One way to create it is to use AbstractTransformerCreationTask, but there are other ways that you can read about here.

public class Employees_NameAndPhone : AbstractTransformerCreationTask<Employee>
{
	public class Result
	{
		public string FirstName { get; set; }

		public double LastName { get; set; }

		public double HomePhone { get; set; }
	}

	public Employees_NameAndPhone()
	{
		TransformResults = employees => from employee in employees 
						select new
						{
							employee.FirstName, 
							employee.LastName, 
							employee.HomePhone
						};
	}
}

  • since transformers work server-side, next logical step would be to send it to the server. More information about how to deploy transformers can be found here.

// save transformer on server
new Employees_NameAndPhone().Execute(store);

  • now, while querying or even loading, we can project our results using appropriate transformer.

Employees_NameAndPhone.Result result = session
	.Load<Employees_NameAndPhone, Employees_NameAndPhone.Result>("employees/1");

IList<Employees_NameAndPhone.Result> results = session
	.Query<Employee>()
	.TransformWith<Employees_NameAndPhone, Employees_NameAndPhone.Result>()
	.ToList();

More examples with detailed descriptions can be found here.