使用Automapper将多个ID属性映射到单个Name属性

时间:2015-01-06 20:44:45

标签: automapper dto

我有一个具有Name属性的User实体,我需要将其链接回DTO中的三个基于Id的属性。

用户实体

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相匹配,使用User.Name排列AlbumDto.ArtistName的正确语法是什么?

2 个答案:

答案 0 :(得分:0)

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

你也可以写一个Test并使用Mapper.AssertConfigurationIsValid();在CreateMap之后,确保创建映射时没有例外。

答案 1 :(得分:0)

我最终选择了不同的路线并跳过了我试图写的自动码代码。

以下是新实体和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
相关问题