我正在创建一个用户类,并希望添加一个ConfirmPassword字段。因为我没有这个字段在我的数据库我如何处理它?我也在使用AutoMapper,我需要做些什么来处理这个额外的字段,例如告诉映射器忽略这个字段吗?
我在这里有我的用户类,我刚刚在好友类中添加了NotMapped属性。这就是我所需要做的吗?或者是否需要任何额外的编码来处理这个场景?
public partial class User
{
public User()
{
//this.DateCreated = DateTime.Now; //set default value
Roles = new HashSet<Role>();
}
public ICollection<Role> Roles { get; set; } //many to many relationship
public int UserId { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public string City { get; set; }
//foreign key
public int CountryId { get; set; }
//navigation properties
public virtual Country Country { get; set; }
//foreign key
public int LanguageId { get; set; }
//navigation properties
public virtual Language Language { get; set; }
public string EmailAddress { get; set; }
public long FacebookId { get; set; }
public DateTime DateCreated { get; set; }
}
//buddy class, validation in here because not supported in Fluent API
//test in ie
//MetadataType decorated class
[MetadataType(typeof(UserMetadata))]
public partial class User
{
}
//Metadata type
internal sealed class UserMetadata
{
[Required]
public string FirstName { get; set; }
[Required]
public string Surname { get; set; }
[Required]
[Remote("IsUsernameAvailable", "Validation")]
[DataType(DataType.Text)]
[DisplayName("Username")]
public string Username { get; set; }
[Required]
public int CountryId { get; set; }
public string Password { get; set; }
[NotMapped]
public string ConfirmPassword { get; set; }
public string City { get; set; }
public int LanguageId { get; set; }
public string EmailAddress { get; set; }
public long FacebookId { get; set; }
public DateTime DateCreated { get; set; }
}
}
编辑:这是我相应的DTO类:
public class UserDTO
{
public int Id { get; set; }
public string FirstName { get; set; }
public string Surname { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string City { get; set; }
public string CountryName { get; set; }
public string LanguageName { get; set; }
public string EmailAddress { get; set; }
public long FacebookId { get; set; }
public DateTime DateCreated { get; set; }
}
ConfirmPassword
字段应该在视图模型类上定义,而不是在实体框架跟踪的域模型对象上定义。由于该值从未存储到数据库中,因此它甚至不应该成为域模型的一部分。
此属性应仅在视图模型类上定义,即映射到Create Account视图的视图模型类。你不需要用AutoMapper做任何特殊的步骤来处理这个字段,因为它不应该是你的域模型的一部分=>当AutoMapper在你的CreateUserViewModel和你的User模型之间进行映射时,它将被忽略。