首页 > 解决方案 > 模型和 DTO 上的 AutoMapper 映射异常

问题描述

我有一个实体框架域模型类及其 DTO 类的映射。

模型:

public class UserAccount : BaseEntity
{
    /// <summary>
    /// Default constructor.
    /// </summary>
    public UserAccount() => Users = new HashSet<User>();

    #region Public Properties

    /// <summary>
    /// The email address of this user account.
    /// </summary>
    [Required]
    [MaxLength(255)]    
    public string Email { get; set; }

    /// <summary>
    /// The password of this user account.
    /// </summary>
    [Required]
    [MaxLength(500)]
    public string Password { get; set; }

    /// <summary>
    /// The verified status of this user account.
    /// </summary>
    public bool Verified { get; set; }

    /// <summary>
    /// The associated list of <see cref="User"/> for this user account.
    /// </summary>
    public virtual ICollection<User> Users { get; set; }

    #endregion

    #region Helpers

    public override string ToString()
    {
        string str = base.ToString();
        str +=
        $"Email: {Email}{Environment.NewLine}" +
        $"Password: {Password}{Environment.NewLine}" +
        $"Verified: {Verified}";
        return str;
    }

    #endregion
}

DTO:

public class UserAccountDto
{
    /// <summary>
    /// The email address of this user account.
    /// </summary>
    [Required]
    [MaxLength(255)]    
    public string Email { get; set; }

    /// <summary>
    /// The password of this user account.
    /// </summary>
    [Required]
    [MaxLength(500)]
    public string Password { get; set; }
}

我已经在 Global.asax 中映射并注册了它们,这是映射代码:

// Domain.
CreateMap<UserAccount, UserAccountDto>();

// DTO.
CreateMap<UserAccountDto, UserAccount>()
    .ForMember(dest => dest.Id, opt => opt.Ignore())
    .ForMember(dest => dest.EntityCreated, opt => opt.Ignore())
    .ForMember(dest => dest.EntityActive, opt => opt.Ignore())
    .ForMember(dest => dest.EntityVersion, opt => opt.Ignore())
    .ForMember(dest => dest.Verified, opt => opt.Ignore())
    .ForMember(dest => dest.Users, opt => opt.Ignore());

我正在尝试将 DTO 映射到域,以便可以使用以下代码将域保存到我的数据库中:

UserAccount userAccount = Mapper.Map<UserAccount>(userAccountDto);

但是我收到此错误:

AutoMapper created this type map for you, but your types cannot be mapped using the current configuration.
UserAccountDto -> UserAccount (Destination member list)
OysterCard.Models.Dto.UserAccount.UserAccountDto -> OysterCard.Models.Security.UserAccount (Destination member list)

Unmapped properties:
Verified
Users
Id
EntityCreated
EntityActive
EntityVersion

我在这里做错了什么?我已经映射了上述属性,所以我不确定它哪里出错了。我对 AutoMapper 很陌生,所以我可能会在某个地方明显出错,但我不确定具体在哪里。

如果有人可以帮助我解决我的问题,我将不胜感激。

谢谢你。

标签: asp.netentity-frameworkautomapper

解决方案


我才意识到出了什么问题。

我的配置在另一个项目中,该项目也通过 Nuget 安装了 AutoMapper,因此,当我初始化我的映射时,它被映射到 AutoMapper 的另一个实例,而不是我在 ASP.NET 的控制器中使用的那个实例项目。

早该发现这个,男生错误 101!


推荐阅读