You are currently browsing legacy 3.0 version of documentation. Click here to switch to the newest 4.2 version.

We can help you with migration to the latest RavenDB

Contact Us Now
see on GitHub

Session: Querying: How to use transformers in queries?

Transformers can be used with session queries using TransformWith method.

Syntax

IRavenQueryable<TResult> TransformWith<TTransformer, TResult>()
	where TTransformer : AbstractTransformerCreationTask, new();

IRavenQueryable<TResult> TransformWith<TResult>(string transformerName);

Parameters
transformerName string Name of a transformer to use.
Return Value
IRavenQueryable Instance implementing IRavenQueryable interface containing additional query methods and extensions.

Example I

// return up to 128 entities from 'Products' collection
// transform results using 'Products_Name' transformer
// which returns only 'Name' property, rest will be 'null'
List<Product> results = session
	.Query<Product>()
	.Where(x => x.Name == "Chocolade")
	.TransformWith<Products_Name, Product>()
	.ToList();

Example II

Loading document inside transformer and projecting results to different type.

public class ProductWithCategoryAndSupplier
{
	public string Name { get; set; }

	public Supplier Supplier { get; set; }

	public Category Category { get; set; }
}

public class Products_WithCategoryAndSupplier : AbstractTransformerCreationTask<Product>
{
	public Products_WithCategoryAndSupplier()
	{
		TransformResults =
			products => from product in products 
						select new
						{
							Name = product.Name,
							Category = LoadDocument<Category>(product.Category),
							Supplier = LoadDocument<Supplier>(product.Supplier)
						};
	}
}

// return 1 entity from 'Products' collection
// transform results using 'Products_WithCategoryAndSupplier' transformer
// project results to 'ProductWithCategoryAndSupplier' class
ProductWithCategoryAndSupplier product = session
	.Query<Product>()
	.Where(x => x.Name == "Chocolade")
	.TransformWith<Products_WithCategoryAndSupplier, ProductWithCategoryAndSupplier>()
	.First();

Assert.Equal("Chocolade", product.Name);
Assert.Equal("Confections", product.Category.Name);
Assert.Equal("Zaanse Snoepfabriek", product.Supplier.Name);