I use the same ViewModel in ASP.NET MVC projects, but for a thousand of records it seems to be better not to retrieve unused records from database. For example, assume UserViewModel for Read, Create and Update situations as shown below:
public class UserViewModel
{
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public bool EmailConfirmed { get; set; }
public virtual int AccessFailedCount { get; set; }
public virtual bool LockoutEnabled { get; set; }
public virtual DateTime? LockoutEndDateUtc { get; set; }
public virtual string PasswordHash { get; set; }
public virtual string PhoneNumber { get; set; }
public virtual bool PhoneNumberConfirmed { get; set; }
public virtual string SecurityStamp { get; set; }
public virtual bool TwoFactorEnabled { get; set; }
}
Read: When displaying the details of a record, I need to retrieve all of the properties except from password (I know I can also retrieve data without ViewModel, but sometimes I need to combine several views in a ViewModel and this is also similar situation).
Create: When creating a new record, I do not need to use Id, EmailConfirmed, AccessFailedCount, etc. Columns.
Update: When updating a record, I do not need to use some properties also.
Under this scene, what is the best approach for using ViewModel? To create a separate ViewModel i.e. ReadUserViewModel, CreateUserViewModel and UpdateUserViewModel or to use the same ViewModel for the same group of data? Any help would be appreciated.
class UserBaseVMthat contains properties that common to all views (for exampleEmail), then have a view model for each view that inherits fromUserBaseVM, e.g.class UserCreateVM : UserBaseVMwill contain properties specific to creating a new user (for exampleConfirmPassword)var model = db.Users.Select(x => new UserVM() { Email = x.Email, ..... });to call the database and project the data into a view model before returning it to the view (or use tools such as automapper