如何反向映射在 Automapper C# 中显式映射的实体的多个成员?
How to reverse map multiple members of an entity that are mapped explicitely in Automapper C#?
我正在开发一个 C# 应用程序,我需要在其中映射 2 个实体。所以,我定义创建地图如下:
CreateMap<Source, Destination>()
.ForMember(dest => dest.FirstName, map => map.MapFrom(src => src.Name.First))
.ForMember(dest => dest.LastName, map => map.MapFrom(src => src.Name.Last))
.ForMember(dest => dest.SSN, map => map.MapFrom(src => src.SSN))
.ForMember(dest => dest.HomePhoneNo, map => map.MapFrom(src => src.HomePhoneNumber()))
.ForMember(dest => dest.Address, map => map.MapFrom(src => src.Address))
.ForMember(dest => dest.MaritalStatus, map => map.MapFrom(src => (int)src.MaritalStatus))
现在,我想做ReverseMap,但是当我为每个成员添加.ReverseMap 时,在下一行成员中,src 和dest 被切换了。那么,有什么方法可以在一个地方为所有成员做ReverseMap吗?
只将一个 ReverseMap()
放在所有自定义映射的末尾。
这对我有用:
using AutoMapper;
class Program
{
static void Main(string[] args)
{
var configuration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<X, Y>()
.ForMember(dest => dest.Bar1, map => map.MapFrom(src => src.Foo1))
.ForMember(dest => dest.Bar2, map => map.MapFrom(src => src.Foo2))
.ReverseMap() ;
});
configuration.AssertConfigurationIsValid();
var mapper = configuration.CreateMapper();
var x1 = new X() { Foo1 = "1", Foo2 = "2"};
var mappedY = mapper.Map<Y>(x1);
var againX = mapper.Map<X>(mappedY);
Console.WriteLine($"{againX.Foo1} {againX.Foo2}");
}
}
class X
{
public string Foo1 { get; set; }
public string Foo2 { get; set; }
}
class Y
{
public string Bar1 { get; set; }
public string Bar2 { get; set; }
}
我正在开发一个 C# 应用程序,我需要在其中映射 2 个实体。所以,我定义创建地图如下:
CreateMap<Source, Destination>()
.ForMember(dest => dest.FirstName, map => map.MapFrom(src => src.Name.First))
.ForMember(dest => dest.LastName, map => map.MapFrom(src => src.Name.Last))
.ForMember(dest => dest.SSN, map => map.MapFrom(src => src.SSN))
.ForMember(dest => dest.HomePhoneNo, map => map.MapFrom(src => src.HomePhoneNumber()))
.ForMember(dest => dest.Address, map => map.MapFrom(src => src.Address))
.ForMember(dest => dest.MaritalStatus, map => map.MapFrom(src => (int)src.MaritalStatus))
现在,我想做ReverseMap,但是当我为每个成员添加.ReverseMap 时,在下一行成员中,src 和dest 被切换了。那么,有什么方法可以在一个地方为所有成员做ReverseMap吗?
只将一个 ReverseMap()
放在所有自定义映射的末尾。
这对我有用:
using AutoMapper;
class Program
{
static void Main(string[] args)
{
var configuration = new MapperConfiguration(cfg =>
{
cfg.CreateMap<X, Y>()
.ForMember(dest => dest.Bar1, map => map.MapFrom(src => src.Foo1))
.ForMember(dest => dest.Bar2, map => map.MapFrom(src => src.Foo2))
.ReverseMap() ;
});
configuration.AssertConfigurationIsValid();
var mapper = configuration.CreateMapper();
var x1 = new X() { Foo1 = "1", Foo2 = "2"};
var mappedY = mapper.Map<Y>(x1);
var againX = mapper.Map<X>(mappedY);
Console.WriteLine($"{againX.Foo1} {againX.Foo2}");
}
}
class X
{
public string Foo1 { get; set; }
public string Foo2 { get; set; }
}
class Y
{
public string Bar1 { get; set; }
public string Bar2 { get; set; }
}