2015-01-06 55 views
2

我有一个带有Name属性的用户实体,我需要将它链接回DTO中的三个基于Id的属性。使用Automapper将多个ID属性映射到单个Name属性

用户实体

public string Name { get; set; } 
public string SSN { get; set; } 

专辑实体

public string Title { get; set; } 
public int Artist { get; set; } // <-- this ties to User.Id 
public int Producer { get; set; } // <-- this ties to User.Id 
public int Designer { get; set; } // <-- this ties to User.Id 
public User User {get; set; } 

AlbumDTO

public string Title { get; set; } 
public int Artist { get; set; } // <-- this ties to User.Id 
public int Producer { get; set; } // <-- this ties to User.Id 
public int Designer { get; set; } // <-- this ties to User.Id 
public string ArtistName { get; set; } // <-- need this to be User.Name 
public string ProducerName { get; set; } // <-- need this to be User.Name 
public string DesignerName { get; set; } // <-- need this to be User.Name 

我试图映射它是这样的:

Mapper.CreateMap<Album, AlbumDto>() 
       .ForMember(dest => dest.ArtistName , opt => opt.MapFrom(s => s.User.Name)); 

但这只是抛出一个映射错误(“无法找到列'User_Id'”)。

通过将AlbumDto.Artist与User.Id进行匹配,将AlbumDto.ArtistName与User.Name对齐的正确语法是什么?

+0

你确定这是一个AutoMapper问题?如果你没有AM查询's.User.Name',会发生什么? –

回答

0

该代码适用于我。我正在使用Automapper 3.3.0

也可以编写测试并使用Mapper.AssertConfigurationIsValid();在CreateMap之后确保映射创建时没有例外。

0

我结束了采取不同的路线,并跳过我试图写的Automapping代码。

这里的新实体和DTO如何变成了:

用户实体

public User() //<-- new code 
     { 
      Albums = new List<Album>(); 
     } 
public string Name { get; set; } 
public string SSN { get; set; } 
public virtual ICollection<Album> Albums { get; set; } //<-- new code 

专辑实体

public string Title { get; set; } 
public int Artist { get; set; } // <-- this ties to User.Id 
public int Producer { get; set; } // <-- this ties to User.Id 
public int Designer { get; set; } // <-- this ties to User.Id 
public User ArtistUser {get; set; } //<-- new code 

映射中的DbContext OnModelCreating()

modelBuilder.Entity<Album>().HasOptional(t => t.ArtistUser) 
       .WithMany(t => t.Albums) 
       .HasForeignKey(d => d.Artist); 

专辑DTO

public string Title { get; set; } 
public int Artist { get; set; } // <-- this ties to User.Id 
public int Producer { get; set; } // <-- this ties to User.Id 
public int Designer { get; set; } // <-- this ties to User.Id 
public string ArtistUserName { get; set; } // <-- new code gets Artist Name from User.Name 
相关问题