C#模型的自定义设置器

Sta*_*tan 15 .net c# entity-framework poco

我不知道如何为C#数据模型制作自定义setter.场景非常简单,我希望我的密码能够使用SHA256功能自动加密.SHA256功能非常有效(我以前曾在大量的项目中使用过).

我已经尝试了几件事,但是当我运行时update-database,似乎它正在递归地执行某些操作并且我的Visual Studio挂起(不发送错误).请帮助我了解如何在模型中默认加密密码.

用我已经尝试过的代码

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

种子

context.Administrators.AddOrUpdate(x => x.Username, new Administrator { Username = "admin", Password = "123" });
Run Code Online (Sandbox Code Playgroud)

Chr*_*ken 33

您需要使用私有成员变量作为后备字段.这允许您单独存储值并在设置器中对其进行操作.

这里有好消息

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);                
        }
    }
}
Run Code Online (Sandbox Code Playgroud)