Skip to content

Merging expressions

jeuxjeux20 edited this page Apr 13, 2021 · 5 revisions

Merging two expressions

You can merge two new X { ... } expressions with the Merge extension method:

Expression<Func<Cat, CatDto>> catDtoExpression = x => new CatDto
{
    Id = x.Id,
    Name = x.Name
};
catDtoExpression.Merge(x => new CatDto
{
    Name = x.Name + " is a great cat!",
    CutenessLevel = x.CutenessLevel
});

This results in the following expression:

x => new CatDto
{
    Id = x.Id,
    Name = x.Name + " is a great cat!",
    CutenessLevel = x.CutenessLevel
}

Merging nested object initializers

When encountering a new X { ... } expression on both sides of an assignment, they both get merged as well:

Expression<Func<Person, PersonDto>> personDtoExpression = x => new PersonDto
{
    Id = x.Id,
    Cat = new CatDto 
    { 
        Id = x.Cat.Id,
        Name = x.Cat.Name
    }
};
personDtoExpression.Merge(x => new PersonDto
{
    Cat = new CatDto
    {
        Name = x.Cat.Name + " is awesome!"
    } 
}),;

And this gives:

x => new PersonDto
{
    Id = x.Id,
    Cat = new CatDto 
    { 
        Id = x.Cat.Id,
        Name = x.Cat.Name + " is awesome!" // !
    }
}

Merging mappers with an expression

This also works with IMapper<TInput, TSource>, using the Merge extension method as well:

var mergedMapper = catDtoMapper.Merge(x => new CatDto
{
    Name = x.Name + " is a great cat!"
})

This methods merges the mapper's Expression with the given expression, and creates a new mapper out of it (using the WithExpression method, which creates an instance of the mapper with the specified expression).