How can I stitch or encrypt a field using EF CodeFirst?

Using EF Code First, how can I interrupt saving a field value so that I can use it? A simple example is the password field:

public class Account
{
    private string _password; 

    public string Password
    {
        get
        {
            return _password;
        }
        set
        {
           _password = MyHashMethod(value);
        }
    }
}

This seems to work when storing the value in the database, but does not work when retrieving the value.

EDIT: Changed _password = MyHashMethod (_password) to MyHashMethod (value) above. The answer below should be made the same correction.

+3
source share
1 answer

I would just do it like this:

public class Account {
    public string HashedPassword { get; set; } 
    public string ClearTextPassword { 
        set { HashedPassword = MyHashMethod(value); }
    }
}

Only HashedPassword is stored in the database.

+6
source

Source: https://habr.com/ru/post/1783494/


All Articles