模型和DTO上的AutoMapper映射异常

时间:2018-12-18 09:56:48

标签: asp.net entity-framework automapper

我有一个Entity Framework域模型类及其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的新手,所以我可能在某个地方犯错了,但我不确定到底在哪里。

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

谢谢。

1 个答案:

答案 0 :(得分:0)

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

我的配置位于另一个项目中,该项目也通过Nuget安装了AutoMapper,因此,当我初始化映射时,它是针对AutoMapper的另一个实例而不是我在Controller中使用的那个实例进行映射的。 ASP.NET项目。

应该早点发现这个小学生错误101!

相关问题