Skip to content

Applying transformations with .Apply()

The Apply() method allows fluent and functional object mutation while keeping your code clean and expressive.

This is especially useful when you need to set technical fields on the backend — such as generating an Id or setting timestamps — without relying on the database or cluttering your logic.


How it works

The method Apply<T>(this T obj, Action<T> apply) executes the provided action and returns the same object, enabling fluent chaining.

public class Product
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public DateTime CreatedAt { get; set; }
}

Practical example

Let’s say you want the Id to be generated in the backend instead of letting the database handle it:

var product = dto.MapTo<Product>()
    .Apply(p => p.Id = Guid.NewGuid())
    .Apply(p => p.CreatedAt = DateTime.UtcNow);

The object is mapped and then updated with additional data — all in a clean, fluent chain.


Benefits

  • Reduces repetitive code
  • Improves code expressiveness
  • Avoids extra helper methods or unnecessary if blocks

Tip

You can use Apply() on any object, not just those created with MapTo<T>().
It’s a great tool for building clean transformation pipelines:

var customer = new Customer()
    .Apply(c => c.Active = true)
    .Apply(c => c.CreatedBy = loggedUser.Name);

Fluent and reusable

With Apply(), you express intent clearly while keeping code concise and maintainable — without sacrificing structure or readability.