【问题标题】:Automapper how to use IgnoreMap attribute with MemberList.Source optionAutomapper 如何将 IgnoreMap 属性与 MemberList.Source 选项一起使用
【发布时间】:2019-10-21 18:30:31
【问题描述】:

如何在 Automapper 9.0 中结合使用基于属性的成员忽略(例如 [IgnoreMap])和 MemberList.Source 选项? IgnoreMap 属性似乎被...忽略 - 以下示例抛出:

public class Source
{
    public string PropertyA { get; set; }
    [IgnoreMap]
    public string IgnoredProperty { get; set; }
}

public class Destination
{
    public string PropertyA { get; set; }

    public string PropertyC { get; set; }
}

public class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<Source, Destination>(MemberList.Source);
    }
}

使用MapperConfiguration.AssertConfigurationIsValid() 进行配置时。它抛出 AssertConfigurationIsValid 就好像[IgnoreMap] 不存在一样:

找到未映射的成员。查看下面的类型和成员。添加一个 自定义映射表达式,忽略,添加自定义解析器,或修改 源/目标类型对于没有匹配的构造函数,添加一个无参数 ctor,添加可选参数,或映射所有构造函数参数 ==================================================== ================ 来源 -> 目的地(来源成员列表) Mapping.Source -> Mapping.Destination(源成员列表)

未映射的属性:IgnoredProperty

我也试过[Ignore][NotMapped]属性,但是结果是一样的。

【问题讨论】:

  • [IgnoreMap] 不适用于源代码验证。
  • @LucianBargaoanu 是记录在案的行为,如果是,他们是否指定了替代方案?
  • 你必须在代码中做,没有属性。当然,您始终可以自己实现。

标签: c# automapper


【解决方案1】:

我没有尝试过自动映射器的属性忽略,我总是使用这个

CreateMap<Source, Destination>.ForMember(x => x.IgnoredProperty, opt => opt.Ignore());

或在这里尝试答案:How to configure Automapper to automatically ignore properties with ReadOnly attribute?

【讨论】:

  • 谢谢,但这不起作用 - IgnoredProperty 不是 Destination 类的成员。
  • @wondra 然后您可以切换应该处理IgnoredProperty 的属性
  • 我认为我们误解了彼此,您示例中的xDestination 类型,而不是Source 类型。显然x 不能用于忽略Source.IgnoredProperty 属性,或者换句话说:示例无法编译。
【解决方案2】:

源中的其他属性会被映射器自动忽略,因此您应该忽略明确忽略的目标属性,因此在您的情况下,您必须执行以下代码:

CreateMap<Source, Destination>.ForMember(x => x.PropertyC , options => options.Ignore());

【讨论】:

  • PropertyC 不是可以忽略的,Automapper 抱怨IgnoredProperty 属性。
猜你喜欢
  • 1970-01-01
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 2020-10-12
相关资源
最近更新 更多