可以使用AutoMapper的ForMember
方法来实现将一个属性映射到两个属性的功能。下面是一个示例代码:
using AutoMapper;
using System;
namespace AutoMapperExample
{
public class SourceClass
{
public int Value { get; set; }
}
public class DestinationClass
{
public int Value1 { get; set; }
public int Value2 { get; set; }
}
class Program
{
static void Main(string[] args)
{
// 创建映射配置
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap()
.ForMember(dest => dest.Value1, opt => opt.MapFrom(src => src.Value))
.ForMember(dest => dest.Value2, opt => opt.MapFrom(src => src.Value));
});
// 创建映射器
var mapper = config.CreateMapper();
// 进行映射
var source = new SourceClass { Value = 10 };
var destination = mapper.Map(source);
// 打印结果
Console.WriteLine($"Value1: {destination.Value1}, Value2: {destination.Value2}");
}
}
}
在上述示例中,我们定义了一个SourceClass
和一个DestinationClass
。SourceClass
有一个属性Value
,而DestinationClass
有两个属性Value1
和Value2
。
通过使用CreateMap
方法,我们可以创建一个映射配置,使用ForMember
方法将Value
属性映射到Value1
和Value2
属性。
然后,我们创建了一个映射器mapper
,并使用mapper.Map
方法将source
对象映射到destination
对象。
最后,我们打印了Value1
和Value2
的值,结果为Value1: 10, Value2: 10
。这表明Value
属性成功映射到了Value1
和Value2
属性。