C# 模型的自定义设置器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12989192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Custom setter for C# model
提问by Stan
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).
我不知道如何为 C# 数据模型制作自定义设置器。场景非常简单,我希望使用 SHA256 功能自动加密我的密码。SHA256 函数运行良好(我之前在无数项目中使用过)。
I've tried couple of things but when I run update-databaseit 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.
我已经尝试了几件事,但是当我运行时,update-database它似乎在递归执行某些操作,并且我的 Visual Studio 挂起(不发送错误)。请帮助我了解如何在模型中默认加密密码。
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" });
采纳答案by Chris Kooken
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.
您需要使用私有成员变量作为支持字段。这允许您单独存储值并在 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);
}
}
}
回答by Abdulsattar Mohammed
The get and set you're using actually create methods called get_Password()and set_Password(password).
您使用的 get 和 set 实际上创建了称为get_Password()and 的方法set_Password(password)。
You'd want the actual password to be stored in a private variable. So, just having a private variable that gets returned and updated by those "methods" is the way to go.
您希望将实际密码存储在私有变量中。因此,只需拥有一个由这些“方法”返回和更新的私有变量就是要走的路。
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);
}
}
}

