I have a model for a User generated by EF from an existing database:
public class User
{
public int Id { get;set; }
public string Name { get;set; }
public string Password { get;set; }
public DateTime Created { get;set; }
public DateTime LastModified { get;set; }
}
I’ve been then creating a UserModel and applying data annotations to add validation. I use AutoMapper to translate between User and UserModel.
I am now trying to create the views, with the following business rules:
- when creating a user, the Created and LastModified fields should not appear in the UI, but they should both be set prior to the model being saved in the repository;
- when editing a user, the Created and LastModified fields should not appear in the UI, but the Created field should be left unchanged and the LastModified field should be updated prior to the model being saved in the repository;
- when editing a user, if the password field is not touched, then the Password field in the model is not changed; if the password field contains a value, that should be used to update the model.
So how can I achieve this, with as little code duplication as possible? For instance, should I have an EditUserModel and a CreateUserModel, inheriting from a base UserModel which has the fields common to both (Id, Name, Password)? Should either model have any reference to Created/LastModified? And particularly, how can I handle the password change requirement?
This is how I usually deal with this situation. For the view model, I’m using only one, the EditUserModel, since it really doesn’t pay off to maintain 3 classes only 1-2 properties are different and in my opinion the view model isn’t THAT important, I’m just being pragmatic. In your case the EditUserModel should look something like this
This model gets passed to a controller and I’d personally use a DDD approach (as a mindset) and have let’s say a domain model which looks like this (it’s based on code i’m actually using)
First time when creating a user
When updating
In the repository (note that I don;t have much experience with EF so this code surely can be optimized)
This is hasty code and all can be improved but let me tell why such ‘complicated’ approach. First of all we have a clearer differention between the layers responsabilities, the view model handles all required to display and to send back data to controller and the domain model is not mingled with the persistence model (EF model). You can change pretty easily the password hashing techqnique and teh creates/last modified stuff is handled where changes really occur. When you start adding more functionality this design will make it much easier for you.
The main goal is clarity and maintainability and dependeing on the usage you can take another approach like updating the user via commands (you send to repository a command to change the name or the password)
Ok i’m finished now 🙂