Custom setter for C# model

.net c# entity-framework poco

Question

I am unable to create a custom setter for the C# data model. The situation is rather straightforward: I want my password to be SHA256-encrypted automatically. The SHA256 function is highly effective (I've used it in a ton of applications).

I've tried couple of things but when I runupdate-database My Visual Studio hangs (don't send error), and it seems like something is being done recursively. Please explain to me how to set the model to automatically encrypt passwords.

What I've previously attempted to code

public class Administrator
{
    public int ID { get; set; }
    [Required]
    public string Username { get; set; }
    [Required]
    public string Password
    {
        get
        {
            return this.Password;
        }

        set
        {
            // All this code is crashing Visual Studio

            // value = Infrastructure.Encryption.SHA256(value);
            // Password = Infrastructure.Encryption.SHA256(value);
            // this.Password = Infrastructure.Encryption.SHA256(value);
        }
    }
}

Seed

context.Administrators.AddOrUpdate(x => x.Username, new Administrator { Username = "admin", Password = "123" });
1
16
10/20/2012 2:05:36 PM

Accepted Answer

As a backing-field, you must utilize a private member variable. This enables you to modify the value in the setter and save it independently.

Excellent data zzzz-9 zzzz

public class Administrator
{
    public int ID { get; set; }

    [Required]
    public string Username { get; set; }

    private string _password;

    [Required]
    public string Password
    {
        get
        {
            return this._password;
        }

        set
        {  
             _password = Infrastructure.Encryption.SHA256(value);                
        }
    }
}
34
10/20/2012 2:10:04 PM

Popular Answer

Your use of get and set really generates methods namedget_Password() and set_Password(password) .

The real password should be kept in a private variable, ideally. Therefore, the best course of action is to just have a private variable that is changed and returned by those "methods".

public class Administrator
{
public int ID { get; set; }
[Required]
public string Username { get; set; }
[Required]
private string password;
public string Password
{
    get
    {
        return this.password;
    }

    set
    {
        this.password = Infrastructure.Encryption.SHA256(value);
    }
}
}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow