Listeners: What are conversion listeners and how to work with them?

Conversion listeners provide users with hook for an additional logic when converting an entity to a document/metadata pair and backwards.

IDocumentConversionListener provides methods to inject custom actions before or after actual document/entity conversion.

public interface IDocumentConversionListener
{
	/// <summary>
	/// Called before converting an entity to a document and metadata
	/// </summary>
	void BeforeConversionToDocument(string key, object entity, RavenJObject metadata);

	/// <summary>
	/// Called after having converted an entity to a document and metadata
	/// </summary>
	void AfterConversionToDocument(string key, object entity, RavenJObject document, RavenJObject metadata);

	/// <summary>
	/// Called before converting a document and metadata to an entity
	/// </summary>
	void BeforeConversionToEntity(string key, RavenJObject document, RavenJObject metadata);

	/// <summary>
	/// Called after having converted a document and metadata to an entity
	/// </summary>
	void AfterConversionToEntity(string key, RavenJObject document, RavenJObject metadata, object entity);
}

Example

Let's consider a case that we want to convert a metadata value provided by RavenDB server to a property of our class. To achieve this we are going to ignore the property after the entity is converted to the document and set the value of this property after the entity is created from the document/metadata pair.

public class Item
{
	public string Id { get; set; }

	public string Name { get; set; }

	public string Revision { get; set; }
}

public class MetadataToPropertyConversionListener : IDocumentConversionListener
{
	public void AfterConversionToDocument(string key, object entity, RavenJObject document, RavenJObject metadata)
	{
		if (entity is Item == false)
			return;

		document.Remove("Revision");
	}

	public void AfterConversionToEntity(string key, RavenJObject document, RavenJObject metadata, object entity)
	{
		if (entity is Item == false)
			return;

		((Item)entity).Revision = metadata.Value<string>("Raven-Document-Revision");
	}

	public void BeforeConversionToDocument(string key, object entity, RavenJObject metadata)
	{
	}

	public void BeforeConversionToEntity(string key, RavenJObject document, RavenJObject metadata)
	{
	}
}