2
我正在创建用户类并希望添加ConfirmPassword字段。由于我的数据库中没有这个字段,我该如何处理它?我也使用AutoMapper,我是否需要做任何事情来处理这个额外的领域,例如告诉映射器忽略这个字段?EF代码优先和确认字段
我在这里有我的用户类,我刚刚在好友类中添加了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; }
}
我正在使用DTO和好友类进行验证。我将如何实现您的建议,因为ConfirmPassword属性需要在类中进行验证。 – user517406
不,我的答案中已经解释了ConfirmPassword属性必须仅位于视图模型上。然后您将验证此视图模型。视图模型验证完成后,您可以使用AutoMapper构建DTO或域模型,或者从视图模型中调用它。但是再一次,ConfirmPassword字段仅在视图模型上有意义。如果你把它放在模型的其他层面,恐怕你做错了。 –
我对模型vs视图模型有点困惑....我有我的模型与数据库交互,然后在UI端使用DTO。 View Model在哪里出现这种情况? – user517406