Automapper is not mapping correctly between two boolean nullable members, with different names. This Always results in Null in the destination. How can this be resolved?
CreateMap<{Product, ProductDto>()
.ForMember(dest => dest.ProductStatus, opt => opt.MapFrom(src => src.Status))
.ReverseMap();
Being called like this,
var productList = _mapper.Map<IEnumerable<ProductDto>, IEnumerable<Product>>(productDtoList);
public class ProductDto
{
public int ProductId{ get; set; }
public string ProductName{ get; set; }
public bool? ProductStatus { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public bool? Status { get; set; }
}
Update: It seems to be working though, when I name both ProductDto and Product as Status
, instead of ProductStatus
on ProductDto
Currently using Net Core 3.1
I created a quick console app and everything worked as expected, so I'm not sure what the problem is. Make sure your configuration is actually being applied to your _mapper
. I can only guess that might be the problem.
class Program
{
static void Main(string[] args)
{
var configuration = new MapperConfiguration(cfg => cfg
.CreateMap<Product, ProductDto>()
.ForMember(dest => dest.ProductStatus, opt => opt.MapFrom(src => src.Status))
.ReverseMap()
);
var mapper = new Mapper(configuration);
var productDtoList = new List<ProductDto>
{
new ProductDto { ProductId = 0, ProductName = "Product 1", ProductStatus = false },
new ProductDto { ProductId = 1, ProductName = "Product 2", ProductStatus = true },
new ProductDto { ProductId = 2, ProductName = "Product 3", ProductStatus = null },
};
var productList = mapper.Map<List<Product>>(productDtoList);
foreach(var product in productList)
{
Console.WriteLine($"{product.ProductId}\t{product.ProductName}\t{product.Status}");
// Output
// 0 Product 1 False
// 1 Product 2 True
// 2 Product 3
}
}
}
public class ProductDto
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public bool? ProductStatus { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public bool? Status { get; set; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.