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