EF Code First和确认字段

时间:2012-12-25 15:19:04

标签: asp.net-mvc entity-framework automapper

我正在创建一个用户类,并希望添加一个ConfirmPassword字段。由于我的数据库中没有此字段,我该如何处理呢?我也在使用AutoMapper,我是否需要做任何事情来处理这个额外的字段,例如告诉mapper忽略这个字段?

我的用户类在这里,我刚刚在好友类中添加了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; }
}

1 个答案:

答案 0 :(得分:2)

ConfirmPassword字段应在您的视图模型类上定义,而不是在Entity Framework跟踪的域模型对象上定义。由于此值永远不会存储到数据库中,因此它甚至不应成为域模型的一部分。

此属性应仅在您的视图模型类上定义,该类是映射到“创建帐户”视图的类。您不需要使用AutoMapper执行任何特殊步骤来处理此字段,因为它不应该是您的域模型的一部分=&gt;当AutoMapper在您的CreateUserViewModel和您的用户模型之间进行映射时,它将被忽略。