繁体   English   中英

你能告诉 AutoMapper 在映射时全局忽略缺失的属性吗?

[英]Can you tell AutoMapper to globally ignore missing properties when mapping?

我有很多实体,到目前为止,我一直在做类似的事情

Mapper.CreateMap<Employee, EmployeeDetailsDTO>()
    .ForSourceMember(mem => mem.NewsPosts, opt => opt.Ignore());

我想告诉 AutoMapper 忽略目标对象中缺少的属性,而不必指定每个属性。 到目前为止,我还没有找到一种方法来使用我的多个 SO 和 Google 搜索。 有人有解决方案吗? 我准备做某种循环或任何事情,只要它可以编写一次并且它会随着模型/dto 更改或添加的属性而扩展。

你什么时候收到错误? 是在您调用AssertConfigurationIsValid吗?

如果是,那么干脆不要调用这个方法

您不必调用此方法,请考虑以下有效的映射:

public class Foo1
{
    public string Field1 { get; set; }
}
public class Foo2
{
    public string Field1 { get; set; }
    public string Field2 { get; set; }
}

Mapper.CreateMap<Foo1, Foo2>();
var foo1 = new Foo1() {Field1 = "field1"};
var foo2 = new Foo2();
Mapper.Map(foo1, foo2);//maps correctly, no Exception

您可能希望为其他映射调用AssertConfigurationIsValid以确保它们是正确的,因此您需要做的是将您的映射组织到配置文件中:

public class MyMappedClassesProfile: Profile
{
    protected override void Configure()
    {
        CreateMap<Foo1, Foo2>();
        //nb, make sure you call this.CreateMap and NOT Mapper.CreateMap
        //I made this mistake when migrating 'static' mappings to a Profile.    
    }
}

Mapper.AddProfile<MyMappedClassesProfile>();

然后,如果您决定要检查映射的有效性(在您的情况下逐案),然后调用

Mapper.AssertConfigurationIsValid(typeof(MyMappedClassesProfile).FullName);

在您的情况和/或任何您调用AssertConfigurationIsValid情况下很重要,您应该使用诸如AutoFixture和单元测试之类的东西来确保您的映射正常工作。 (这是AssertConfigurationIsValid的意图)

wal 的回答中建议“不要调用 AssertConfigurationIsValid()”是不安全的,因为它会隐藏映射中的潜在错误。
最好显式忽略类之间的映射,您确信所有需要的属性都已正确映射。 您可以使用在AutoMapper 中创建的扩展:“忽略其余部分”? 回答:

var config = new MapperConfiguration(cfg =>
{
    cfg.CreateMap<Src, Dest>();
     cfg.IgnoreUnmapped<Src, Dest>();  // Ignores unmapped properties on specific map
});

不带参数的重载cfg.IgnoreUnmapped(this IProfileExpression profile)忽略所有映射上的未映射属性,不推荐使用,因为它也隐藏了所有类的任何潜在问题。

如果我有许多具有许多属性的类要忽略,我不希望在调用 AssertConfigurationIsValid() 时出现异常,但更喜欢在日志中报告它,只是查看所有未映射的属性是有意遗漏的。 因为 AutoMapper 没有公开进行验证的方法,所以我捕获了 AssertConfigurationIsValid 并将错误消息作为字符串返回。

    public string ValidateUnmappedConfiguration(IMapper mapper)
    {
        try
        {
            mapper.ConfigurationProvider.AssertConfigurationIsValid();
        }
        catch (AutoMapperConfigurationException e)
        {
              return e.Message;
        }
        return "";
    }

我正在从单元测试调用 ValidateUnmappedConfiguration 方法

   [TestMethod]
    public void LogUmmappedConfiguration()
    {
        var mapper = new MapperConfiguration((cfg =>
        {
            cfg.AddProfile(new AutoMapperProfile());
        })).CreateMapper();
        var msg=ValidateUnmappedConfiguration(mapper) ;
        if (!msg.IsNullOrBlank())
        {
            TestContext.WriteString("Please review the list of unmapped fields and check that it is intentional: \n"+msg);
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM