Код: Выделить всё
/// This is where the string? -> string? mapping is required.
class ARequestModel {
string? ForeignKeyId
}
class ADbModel {
string? ForeignKeyId
}
Код: Выделить всё
/// This is where the string? -> string mapping is required
class BDbModel {
string? Value;
}
class BResponseModel
{
// This should always be at least string.Empty
string Value;
}
Код: Выделить всё
// Empty string is converted to null. This is used to unset values in FK Ids.
CreateMap().ConvertUsing((src, dest) => src == string.Empty ? null : src ?? dest);
// null string is coerced to empty string for backward compatibility
CreateMap().ConvertUsing((src, dest) => string.IsNullOrEmpty(dest) ? src ?? string.Empty : src ?? dest);
Хотя я ожидаю, что оба преобразователя значений будут работать, выполняется только последнее преобразование. >
Шаги по воспроизведению
Код: Выделить всё
[Fact]
public void Map_UpdateRequestModelAndPage_UnsetsPlanId()
{
PageDbModel page = new PageDbModel
{
Id = "ID",
CreatedAt = DateTime.UtcNow,
UserId = "USER_ID",
PlanId = "PLAN_ID"
};
PageUpdateRequestModel updateRequestModel = new PageUpdateRequestModel
{
// ignored
UserId = null,
// results in null destination
MaintenancePolicyId = ""
};
PageDbModel newPage = _mapper.Map(updateRequestModel, page);
Assert.Equal(page.UserId, newPage.UserId);
Assert.Null(newPage.MaintenancePolicyId);
}
[Fact]
public void Map_MetadataToMetadataResponseWithNullValue_ReturnsEmptyStringValue()
{
MetadataDbModel metadata = new MetadataDbModel {
Id = "ID",
CreatedAt = DateTime.UtcNow,
UpdatedAt = DateTime.UtcNow,
Key = "Key",
Value = null
};
var responseModel = _mapper.Map(metadata);
Assert.Equal(string.Empty, dto.Value);
}
Подробнее здесь: https://stackoverflow.com/questions/789 ... automapper
Мобильная версия