2014-05-23 99 views
-2

我有兩個源對象:映射兩個源對象到三個對象

public class Book 
{ 
    public int Id {get;set;} 
    public IList<Unity> Unities {get;set;} 
} 

public class Unity 
{ 
    public int Id {get;set;} 
    public string Title {get;set;} 
} 

和三個目標對象:

public class DtoBook 
{ 
    public int Id {get;set;} 
    public DtoOrganization Organization {get;set;} 
} 

public class DtoOrganization 
{ 
    public int Id {get;set;} 
    public IList<DtoUnity> Unities {get;set;} 
} 

public class DtoUnity 
{ 
    public int Id {get;set;} 
    public string Title {get;set;} 
} 

我想映射兩個源對象簿和統一到三個dto對象,但不存在組織源對象。我怎麼用Automapper來做到這一點?

謝謝!

後我的實際代碼Automapper代碼:

public static void Configure() 
{ 
    Mapper.Reset(); 

    Mapper.CreateMap<Unity, Model.Organization>(); 

    Mapper.CreateMap<Book, Model.Manifest>() 
      .ForMember(x => x.Version, y => y.UseValue("1.1"));     

    Mapper.AssertConfigurationIsValid(); 
} 

public static Model.Manifest Map(Book book) 
{ 
    Configure(); 
    Model.Manifest dtoManifest = Mapper.Map<Book, Model.Manifest>(book); 
    return dtoManifest; 
} 
+1

看看'AutoMapper'。 – rosko

+0

這裏是一個鏈接:http://automapper.codeplex.com/ –

+0

但是,我什麼都看不到! –

回答

0

如果我沒錯過任何東西,這可能是這樣的(這是如果你不想學習如何AutoMapper作品簡單的方法):

class Program 
{ 
    static void Main(string[] args) 
    { 
     var sampleBook = new Book { 
      Id = 1, 
      Unities = new List<Unity> { 
       new Unity { Id = 2, Title = "Title of unity" }, 
       new Unity { Id = 3, Title = "Title of unity" } 
      } 
     }; 

     var ourBookDto = new DtoBook 
     { 
      Id = sampleBook.Id, 
      Organization = new DtoOrganization 
      { 
       Id = 666, // i don't know from where do you want to obtain this id 
       Unities = sampleBook.Unities.Select(u => new DtoUnity { 
        Id = u.Id, 
        Title = u.Title 
       }).ToList() 
      } 
     }; 

     Console.ReadLine(); 
    } 
} 

但是,如果您的課程變得更復雜,這可能會有點骯髒,所以請嘗試使用AutoMapper

+0

我想使用Automapper,但我學到了它,但我無法使用Automapper執行此映射。 –

+0

然後顯示你的代碼? – rosko

+0

我發佈了它,但問題是我不知道如何映射不存在的DtoOrganization作爲源。謝謝! –