【问题标题】:Using Automapper to map multiple ID properties to single Name property使用 Automapper 将多个 ID 属性映射到单个 Name 属性
【发布时间】:2015-01-06 20:44:45
【问题描述】:

我有一个带有 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; }

相册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 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 对齐的正确语法是什么?

【问题讨论】:

  • 您确定这是 AutoMapper 问题吗?如果您在没有 AM 的情况下查询 s.User.Name 会发生什么?

标签: automapper dto


【解决方案1】:

该代码对我有用。我正在使用 Automapper 3.3.0

您也可以编写一个测试并使用 Mapper.AssertConfigurationIsValid();在 CreateMap 之后确保映射创建无异常。

【讨论】:

    【解决方案2】:

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

    以下是新实体和 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-11
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-31
      • 1970-01-01
      相关资源
      最近更新 更多