Models represent domain or database entities. View models shape data specifically for a view or API response—avoid exposing internal fields or navigation properties directly to clients.
Why separate view models
- Views need computed fields (
FullName, formatted dates) - Forms need fields not on the entity (
ConfirmPassword) - APIs need stable contracts decoupled from EF entities
public class RegisterViewModel {
public string Email { get; set; } = "";
public string Password { get; set; } = "";
public string ConfirmPassword { get; set; } = "";
}
Mapping
Map entity ↔ view model in the controller or a dedicated mapper (manual, AutoMapper, or Mapster)—keep EF entities out of Razor when possible.
Important interview questions and answers
- Q: Entity vs DTO vs view model?
A: Entity maps to DB; DTO crosses API boundaries; view model fits a specific UI screen. - Q: Over-posting attack?
A: Binding directly to entities lets attackers set privileged fields—use view models with whitelisted properties.
Self-check
- Why not pass EF entities to every Razor view?
- What field belongs on RegisterViewModel but not User entity?
Interview prep
- What is over-posting?
Binding directly to entities lets attackers set privileged fields (e.g. IsAdmin)—use view models with whitelisted properties for input.