我有很多实体,到目前为止,我一直在做类似的事情
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
的意图)
关于c# - 你能告诉 AutoMapper 在映射时全局忽略缺失的属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13360712/