[C#.NET] 使用 AutoMapper 進行深複製

[C#.NET] 使用 AutoMapper 建立兩個相同型別但不同執行個體的物件

以下的寫法會讓 source,target 兩個參考同一份記憶體,target.Age 改變連帶影響 source.Age


public void 相同型別_同一執行個體()
{
    Member source = new Member() { Name = "yao", Age = 30 };
    Member target = new Member();
    target = Mapper.Map(source, target);
    target.Age = 29;
    Assert.AreEqual(29, source.Age);
    Assert.AreEqual("yao", source.Name);

    Assert.AreEqual(29, target.Age);
    Assert.AreEqual("yao", target.Name);
}

 

我一直以為 AutoMapper 無法處理相同型別但不同型別的資料轉移,原來相同型別也是要定義Mapper.CreateMap<Member, Member>();

以下的寫法就會建立兩個相同型別但不同執行個體的物件


public void 相同型別資料轉移()
{
    Mapper.CreateMap<Member, Member>();
    Member source = new Member() { Name = "yao", Age = 30 };
    Member target = new Member();
    Mapper.Map<Member, Member>(source, target);
    Assert.AreEqual(30, source.Age);
    Assert.AreEqual("yao", source.Name);

    Assert.AreEqual(30, target.Age);
    Assert.AreEqual("yao", target.Name);
}

 

我變更 target.Age 的狀態不會影響 source.Age,所以的確是兩個不同的執行個體,今天才知道原來相同型別也要調用 Mapper.CreateMap


public void 相同型別_不同執行個體()
{
    Mapper.CreateMap<Member, Member>();
    Member source = new Member() { Name = "yao", Age = 30 };
    Member target = new Member();
    Mapper.Map(source, target);
    target.Age = 29;
    Assert.AreEqual(30, source.Age);
    Assert.AreEqual("yao", source.Name);

    Assert.AreEqual(29, target.Age);
    Assert.AreEqual("yao", target.Name);
}


文章出自:http://www.dotblogs.com.tw/yc421206/archive/2015/04/21/151112.aspx

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo