自二传手的C#模型 [英] Custom setter for C# model

查看:115
本文介绍了自二传手的C#模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道如何使C#的数据模型定制的setter。该方案是非常简单的,我想我的密码与SHA256功能被自动加密。 SHA256功能工作得非常好(我用在项目之前极大数)。



我试过几件事情,但是当我运行更新数据库现在看来,这是递归地做一些与我的Visual Studio挂起(不发送错误)。请帮助我了解如何使密码默认模型进行加密。



代码什么我已经试过



 公共类管理员
{
公众诠释ID {搞定;组; }
[必填]
公共字符串用户名{获得;组; }
[必填]
公共字符串密码
{
得到
{
返回this.Password;
}


{
//所有这些代码崩溃的Visual Studio

//值= Infrastructure.Encryption.SHA256(值);
//密码= Infrastructure.Encryption.SHA256(值);
// this.Password = Infrastructure.Encryption.SHA256(值);
}
}
}



种子

  context.Administrators.AddOrUpdate(X => x.Username,新署长{用户名=admin的,密码=123}); 


解决方案

您需要使用私有成员变量作为后盾-领域。这使您可以分别存储的价值,并操纵它的制定者。



好信息的here

 公共类管理员
{
公INT ID {搞定;组; }

[必填]
公共字符串用户名{获得;组; }

私人字符串_password;

[必填]
公共字符串密码
{
得到
{
返回this._password;
}


{
_password = Infrastructure.Encryption.SHA256(值);
}
}
}


I don't know how to make custom setter for C# data model. The scenario is pretty simple, I want my password to be automatically encrypted with SHA256 function. SHA256 function works very well (I've used in in gazillion of projects before).

I've tried couple of things but when I run update-database it seems it's doing something recursively and my Visual Studio hangs (don't send error). Please help me understand how to make passwords be encrypted by default in model.

Code with what I've already tried

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" });

解决方案

You need to use a private member variable as a backing-field. this allows you to store the value separately and manipulate it in the setter.

Good information here

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);                
        }
    }
}

这篇关于自二传手的C#模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆