Skip to content

Merging expressions

jeuxjeux20 edited this page Mar 20, 2020 · 5 revisions

Merging 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
}

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

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).

Clone this wiki locally