asp.net - 模型和 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 很陌生,所以我可能会在某个地方明显出错,但我不确定具体在哪里。
如果有人可以帮助我解决我的问题,我将不胜感激。
谢谢你。
解决方案
我才意识到出了什么问题。
我的配置在另一个项目中,该项目也通过 Nuget 安装了 AutoMapper,因此,当我初始化我的映射时,它被映射到 AutoMapper 的另一个实例,而不是我在 ASP.NET 的控制器中使用的那个实例项目。
早该发现这个,男生错误 101!
推荐阅读
- linux - 使用 mono 和 mono-fastcgi-server4 结合 NGINX 在 Linux 上运行 ASP.NET 应用程序
- sql-server - 在 ResultSet 中检索数据返回“”。SQL 服务器 + 安卓工作室
- python - sdist 中的模块名称动态
- javascript - 在 NestJS 中添加标头 HttpRequest
- javascript - 没有视图的 Aurelia 模型在注销时返回错误
- python - 损坏的管理面板在 Django 中使用自定义字段扩展用户模型
- android-studio - 尝试在 Android Studio 中为颤振项目应用飞镖支持时出现问题
- ios - 在 Objective C 中调用 Swift 函数
- java - 将 String 和 Int 添加到同一个列表
- r - 使用 group_by 时添加总体平均值