在自动映射程序中,不会自动忽略目标类型的只读集合属性



我正在使用AutoMapper v9.0.0。 由于非集合只读属性(仅具有 getter 的属性(在目标类型上会自动忽略,因此我希望集合属性也是如此。 但是,断言映射器配置时会引发异常。 要进一步澄清,请参阅下面的代码。 这是设计使然还是错误?

class Program
{
static void Main(string[] args)
{
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<SourceType, DestinationTypeWithGetterOnly>();
});
//valid
config.AssertConfigurationIsValid();
config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<SourceType, DestinationTypeWithGetterOnlyArray>();
});
//throws exception Unmapped properties: CalculatedArray
config.AssertConfigurationIsValid();
}
}
class SourceType { }
class DestinationTypeWithGetterOnlyArray
{
public string[] CalculatedArray => new string[0];
}
class DestinationTypeWithGetterOnly
{
public string CalculatedProperty => string.Empty;
}

在 github 上引用@LucianBargaoanu

通过设计。您可以使用ForAllMapsForAllMembersForAllPropertyMaps来实现您想要的。或者也许ShouldMapField\ShouldMapProperty.例如

cfg.ShouldMapProperty = property => property.CanWrite;

最新更新