Auto Mapper是一个用于将一个对象的值映射到另一个对象的库。在使用Auto Mapper时,我们可以使用构造函数初始化映射来配置对象之间的映射关系。
以下是一个使用Auto Mapper构造函数初始化映射的示例代码:
using AutoMapper;
public class SourceClass
{
public string Property1 { get; set; }
public int Property2 { get; set; }
}
public class DestinationClass
{
public string PropertyA { get; set; }
public int PropertyB { get; set; }
}
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap()
.ForMember(dest => dest.PropertyA, opt => opt.MapFrom(src => src.Property1))
.ForMember(dest => dest.PropertyB, opt => opt.MapFrom(src => src.Property2));
}
}
public class Program
{
public static void Main()
{
var config = new MapperConfiguration(cfg => cfg.AddProfile());
var mapper = config.CreateMapper();
var source = new SourceClass { Property1 = "Value 1", Property2 = 2 };
var destination = mapper.Map(source);
Console.WriteLine($"PropertyA: {destination.PropertyA}");
Console.WriteLine($"PropertyB: {destination.PropertyB}");
}
}
在上面的示例中,我们定义了一个源类SourceClass和一个目标类DestinationClass。然后,我们创建了一个MappingProfile类,该类继承自AutoMapper的Profile类,并在构造函数中使用CreateMap方法来配置SourceClass到DestinationClass的映射关系。在映射配置中,我们使用ForMember方法来指定属性之间的映射关系。
然后,我们在Main方法中创建了一个MapperConfiguration对象,并通过AddProfile方法将MappingProfile添加到配置中。然后,我们使用配置创建了一个Mapper对象,并使用Map方法将源对象source映射到目标对象destination。
最后,我们输出目标对象的属性值,验证映射是否正确。
请注意,为了运行上述示例代码,您需要在项目中安装AutoMapper库。可以使用NuGet包管理器或在项目文件中手动添加对AutoMapper的引用。
希望上述解决方法对您有所帮助!
上一篇:Auto Mapper 错误 - “未为此对象定义无参数的构造函数”。
下一篇:Auto Mapper在System.Web.IHttpModule上抛出ReflectionTypeLoadException异常。