简体   繁体   中英

Database field with custom non-editable values

I'm pretty new to Entity Framework, so I'm not figuring out how to solve my problem. I have a User entity, as follows:

public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Checksum
{
    get
    {
        return Checksum;
    }

    set
    {
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] originalBytes = ASCIIEncoding.Default.GetBytes(this.Email);
        byte[] encodedBytes = md5.ComputeHash(originalBytes);

        Checksum = BitConverter.ToString(encodedBytes);
    }
}

The field Checksum will not have user input; I want him to be determined by some logic (the one present at his setter). I'll use it for security checking when I need to update some users sensible data.

I'm on the right path? What's the right way to do this?

Thanks in advance!

A setter that does not use value anywhere in its body is an indicator of misusing the technology. If a field is read-only, provide only a getter for it. Do not provide a setter if you plan to discard the value being set. Instead, decide on the value(s) upon which the calculated one is dependent, and move the setting logic for your Checksum into their setters.

Taking your class is an example, the only dependency here is the Email property. You can change your class as follows:

public int ID { get; set; }
public string Name { get; set; }
private string email;
public string Email {
    get { return email; }
    set { email = value; UpdateChecksum(); }
}
public string Username { get; set; }
public string Password { get; set; }
private string checksum;
public string Checksum {
    get { return checksum; }
}
private void UpdateChecksum() {
    MD5 md5 = new MD5CryptoServiceProvider();
    byte[] originalBytes = ASCIIEncoding.Default.GetBytes(email);
    byte[] encodedBytes = md5.ComputeHash(originalBytes);
    checksum = BitConverter.ToString(encodedBytes);
}

Note how UpdateChecksum is moved into a separate method. This is useful in situations when you have multiple dependencies: rather than embedding the logic into the individual setters, it is better to move it into a method, and call it as needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM