Paramount
Paramount

Reputation: 1107

MVC 3 Entity Model - adding methods?

What would be the best way to add methods to an Entity model.

Such-as, I have a User model and I would like to add a method to the class that would hash passwords.

I have tried making a UserHelper class that extends User but this seems almost counterproductive.

Upvotes: 2

Views: 2014

Answers (2)

Tomas Aschan
Tomas Aschan

Reputation: 60664

Although partial classes and extension methods definitely can serve your purpose here, I think in this specific case you're better off handing over responsibility for password hashing to an authentication service of some sort, rather than letting your model implement that logic. The service will then take for example a username and a password (in plain text, not yet hashed) as input, and return an IPrincipal on a successful authentication attempt, and something else otherwise (throw exception, return null, whatever you like to do to indicate that the authentication attempt failed).

Simplified, I'd call the service like so:

IPrincipal user = _authService.Authenticate(username, password);
if (user == null)
{
    ShowErrorMessage("No such user!");

}
else
{
    ShowStatusMessage("Login successful!");
}

This service will also handle creating new users, deleting users etc - perhaps contacting the database through a repository that uses EF. (Your EF model will in that case require a property to store the hashed password, but the hashing itself does not take place in the model - it is done by the service).

Upvotes: 3

Esteban Araya
Esteban Araya

Reputation: 29664

If EF classes are not already partial classes, you could modify the T4 template to make them partial classes.

A partial class is a class that's defined across multiple files. At compile time, the compiler builds the class definition from all files. Partial classes are most commonly used to add code to classes that are generated through automated tools (and are normally destroyed each time the generation runs), such as the T4 template for EF.

With a partial class, as mentioned above, you could then add your methods on a separate file to the class you're trying to "extend".

Having said all of this, you may also consider extension methods.

Extension methods are a neat syntax/compiler trick to extend the functionality of types you can't (eg. you don't own the code or cant' subclass them) modify. By writing an extension method, you're basically writing a static method that will be called as if it was an instance method of the type you just extended.

I think either option is almost just as good, but I'd lean for the partial class method.

Upvotes: 3

Related Questions