c# - Automapper along with generics and mapping missing properties
问题描述
I'm trying to use a generic mapper for mapping two objects. So I have setup Automapper in this way which comes from the documentation:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap(typeof(Source<>), typeof(Destination<>));
});
mapper = config.CreateMapper();
Now everything works well in the case if the source and destination have the same properties and if I'm going from more properties on the source side to less properties on the destination. However if the source has less properties than the destination than I get an error:
Value ---> AutoMapper.AutoMapperConfigurationException: Unmapped members were found. Review the types and members below.
My question is there a way I could ignore these properties even though I won't know what they are at compile time?
Source:
public class Source<T>
{
public T Value { get; set; }
}
public class Destination<T>
{
public T Value { get; set; }
}
public class DataObject1
{
public int Id { get; set; }
public string Code { get; set; }
}
public class DataObject2
{
public int Id { get; set; }
public string Code { get; set; }
public string ActiveFlag { get; set; }
}
Here is my Test Code:
var data = new DataObject1() { Id = 10, Code = "Test" };
var source = new Source<DataObject1> { Value = data };
var dest = mapper.Map<Source<DataObject1>, Destination<DataObject2>>(source);
Assert.AreEqual(dest.Value.Id, 10);
解决方案
如果您像这样配置映射器时映射DataObject1
到,您的映射将成功:DataObject2
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap(typeof(Source<>), typeof(Destination<>));
cfg.CreateMap<DataObject1, DataObject2>();
});
...或者您是否试图避免在编译时知道您可能需要映射DataObject1
到DataObject2
?
推荐阅读
- azure - 标记 Azure Databricks 的托管资源组
- angular - 具有多个模块的嵌套 Angular 组件 (Jhipster)
- mysql - 试图链接两个表,但在一个字段中获取所有信息
- python - 子python进程卡住了
- elasticsearch - 如何在elasticsearch中查找字段所属的索引?
- python - 熊猫合并列重复和总和值
- python - 如何从超类方法初始化子类?
- aws-lambda - Serverless framework - Lambda function with Authorizer COGNITO_USER_POOLS always return "Unauthorized"
- swift - 使用映射创建一个对象数组,其中包含另一个对象数组的少量对象属性
- odbc - Snowflake Linux ODBC 驱动程序