Domanda

I use Entity Framework, so almost all my models are in fact the database. However, sometimes I want to pass to the view a simpler object that is not necessary a database model with all the properties.

For example, I have this model :

int ID
string name
string email
string country
string username
string password

When I pass a model to the login view, I only need the username and password. Thus, I thought about creating a simplified model with only username and password.

My questions :

1) What's the best way to standardize this ? Any best practice ? 2) Can I use inheritance to avoid repeating properties like username / password ? 3) Where I put this non-database model ... in wich cs file ? 4) And what about the name of this simplified model ?

Thank you !

È stato utile?

Soluzione

Yeah you can use ViewModels.

These are regular classes that contain properties that you need for your view. And these properties could be a subset of a model or the combination of multiple models.

For the login view you could create a LoginViewModel

public class LoginViewModel
{
  public int UserId {get; set;}

  [Required]
  public string Username {get; set;}  //included required attribute for username

  public string Password {get; set;}

}

You can now project your viewmodel from your database query (or any other source).

ViewModels are very helpful as in many cases the views typically don't map one to one with models or may be need annotations that you are not willing to add to your models directly.

So many great uses.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top