简体   繁体   中英

Do models need to mirror a database in MVC3?

I'm learning to use the MVC 3 Framework, but I'm having some problems understanding some concepts. I ask this question because I was trying to understand the code generated by the "Internet Application Template" At the AccountModels.cs file in the RegisterModel we find:

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }

It's obvious you won't have Password and ConfirmPassword fields in your database, you'll just have a Password field. So, why this model doesn't mirror a database? What am I missing?

That's a view model, not a model. A view model shouldn't mirror any database. A view model doesn't even know what a database is. A view model is something that you design in order to meet the requirements of a specific view. It is a class that a controller action passes to a view.

When talking about models, we usually talk about domain models or domain entities. Those match your business requirements.

So here's the usual flow of a controller action:

  1. It fetches a domain model from the service layer
  2. It maps/converts this domain model into a view model
  3. It passes the view model to the view

and the other way around:

  1. It takes a view model from a view
  2. It maps/converts this view model back to a domain model
  3. It passes the domain model to the service layer for processing

So a single domain model could have multiple view model representations. And a single view model could be mapped to multiple domain models.

A Model does not have to match the database. You will generally have models of database tables, but also models containing information relevant to a specific page (called a View in MVC), such as the login page.

Models can contain both of these; representing a database table AND view specific information. These are sometimes referred to as ViewModels.

Any information you might send to a view can be represented in a model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM