【问题标题】:In AutoMapper, read only collection properties on the destination type are not automatically ignored在 AutoMapper 中,目标类型上的只读集合属性不会被自动忽略
【发布时间】:2020-07-18 04:52:09
【问题描述】:

我正在使用 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;
}

【问题讨论】:

  • 这有点道理,因为您可以用值填充数组元素。
  • 在 10.0 中,所有没有 setter 的集合属性都将被默认映射。

标签: c# automapper


【解决方案1】:

github上引用@LucianBargaoanu

按设计。您可以使用ForAllMapsForAllMembersForAllPropertyMaps 来实现您想要的。或者ShouldMapField\ShouldMapProperty。例如,

cfg.ShouldMapProperty = property => property.CanWrite;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-23
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多