Existing target object
If an existing object instance should be used as target, you can define the mapping method as void with the target as second parameter:
- Declaration
- Usage
[Mapper]
public partial class CarMapper
{
public partial void UpdateCarDto(Car car, CarDto dto);
}
var mapper = new CarMapper();
var car = new Car { NumberOfSeats = 10, ... };
var dto = new CarDto();
mapper.UpdateCarDto(car, dto);
dto.NumberOfSeats.Should().Be(10);
Merge objects
To merge two objects together, AllowNullPropertyAssignment
can be set to false
.
This ignores all properties on the source with a null
value.
- Declaration
- Usage
- Generated code
[Mapper(AllowNullPropertyAssignment = false)]
static partial class FruitMapper
{
public static partial void ApplyUpdate(FruitUpdate update, Fruit fruit);
}
class Fruit { public required string Name { get; set; } public required string Color { get; set; } }
record FruitUpdate(string? Name, string? Color);
FruitMapper.ApplyUpdate(myUpdateRequest, myFruit);
static partial class FruitMapper
{
public static partial void Update(global::FruitUpdate update, global::Fruit fruit)
{
if (update.Name != null)
{
fruit.Name = update.Name;
}
if (update.Color != null)
{
fruit.Color = update.Color;
}
}
}
See also null value handling.
The MappingTarget
attribute allows setting the first method parameter as mapping target:
- Declaration
- Usage
[Mapper(AllowNullPropertyAssignment = false)]
static partial class FruitMapper
{
public static partial void ApplyUpdate([MappingTarget] this Fruit fruit, FruitUpdate update);
}
class Fruit { public required string Name { get; set; } public required string Color { get; set; } }
record FruitUpdate(string? Name, string? Color);
myFruit.ApplyUpdate(myUpdateRequest);
See also extension methods.