我是MVC框架的新手。我正在使用entityframework DBcontext来执行数据库相关的操作。我这样做 的 的EntityFramework - >的DbContext - >模型 - >控制器 - >查看的。 我直接绑定模型来查看。例如有表名 UserProfile ,我创建了与Model相同的Model和colum作为Model的属性。我正在从 Userprofile 中收集记录集,并将此集合直接绑定到View。 这是模型
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
[DisplayName("ID")]
public long UserId { get; set; }
private string _UserName;
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
public string Thalassemic
{
get;
set;
}
[Display(Name = "Your First Name")]
[Required(ErrorMessage = "First Name is Required.")]
[StringLength(30, ErrorMessage = "First Name must be {2}-{1} to long", MinimumLength = 2)]
[RegularExpression("^[a-zA-z ]+$", ErrorMessage = "First name must contain only characters")]
public string FirstName { get; set; }
[Display(Name = "Your Last Name")]
[Required(ErrorMessage = "Last Name is Required.")]
[RegularExpression("^[a-zA-z ]+$", ErrorMessage = "Only characters are allowed.")]
[StringLength(20, ErrorMessage = "First Name must be {2}-{1} to long", MinimumLength = 2)]
public string LastName { get; set; }
[Required(ErrorMessage = "Email Address is Required.")]
[StringLength(250, ErrorMessage = "{0} must be {2}-{1} to long", MinimumLength = 4)]
[Display(Name = "Email Address")]
[DataType(DataType.EmailAddress, ErrorMessage = "Please enter a valid email-address.")]
[RegularExpression("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", ErrorMessage = "Please enter a valid email-address.")]
//todo: re-think about updating email address as we are user email as login id and this can't change
public string Email { get; set; }}
我是否应该使用此DTO对象将数据与视图绑定
public class UserProfileDTO
{
public long UserId { get; set; }
private string _UserName;
public string UserName
{
get { return _UserName; }
set { _UserName = value; }
}
public string Thalassemic
{ get;
set;
}
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
}
基于以上我想知道这是正确的方法吗?如果不是那么最佳做法是什么?
答案 0 :(得分:3)
在MVC中通常不鼓励使用数据库POCO类作为模型,而不是仅包含视图所需数据的视图模型。想象一下,您有一个包含30多个字段的User
条记录,但您只想显示Username
,您只需创建一个UsernameViewModel
:
public class UsernameViewModel
{
public string Username { get; set; }
}
它更清晰,因为您只是向客户端发送您需要的字段。
答案 1 :(得分:0)