问题
Code First
class Woman
{
public string Name { get; set; }
}
class Family
{
public string SweetName { get; set; }
public Woman Wife { get; set; }
}
class MyProfile : Profile
{
public MyProfile()
{
CreateMap<Woman, Woman>();
CreateMap<Family, Family>()
.ForMember(d => d.Wife, o => o.UseDestinationValue());
}
}
class Program
{
static void main()
{
// Initialize
var ce = new MapperConfigurationExpression();
ce.AddProfile(new MyProfile());
var mapper = new MapperConfiguration(ce).CreateMapper();
var oldWoman = new Woman { Name = "Alice" };
var newWoman = mapper.Map<Woman>(oldWoman);
Console.WriteLine($"oldWoman.Equals(newWoman) : {oldWoman.Equals(newWoman)}");
// false
var oldFamily = new Family { SweetName = "family one", Wife = oldWoman };
var newFamily = mapper.Map<Family>(oldFamily);
Console.WriteLine($"oldFamily.Equals(newFamily) : {oldFamily.Equals(newFamily)}");
// false
Console.WriteLine($"oldFamily.Wife.Equals(newFamily.Wife) : {oldFamily.Wife.Equals(newFamily.Wife)}");
// false
// here i wanna reference of oldfamily.wife pass to newfamily.wife's
}
}
I have set UseDestinationValue(), it doesn't work?
if I don't create woman map, the two wife's reference is equal.
like this:
class MyProfile : Profile
{
public MyProfile()
{
//CreateMap<Woman, Woman>();
CreateMap<Family, Family>();
//.ForMember(d => d.Wife, o => o.UseDestinationValue());
}
}
PS. no creating woman map and UseDestinationValue is unnecessary. two wife's reference is equal without creating woman map and using UseDestinationValue method.
How to pass the reference in this case with using create a map of woman class?
Updated 1
A strange way to solve this :
class MyProfile : Profile
{
public MyProfile()
{
CreateMap<Woman, Woman>();
CreateMap<Family, Family>()
.AfterMap((s, d) => d.Wife = s.Wife);
}
}
it works, but it's not the ultimate way obviously.
it has been mapped. XD
do expect mapping after doing unexpected mapping?
来源:https://stackoverflow.com/questions/56611542/automapper-cannot-mapping-reference-or-using-usedestinationvalue