Wednesday, 17 April 2013

MVC4 Decouple View Data from Database (e.g. for encryption)

The problem: I want to display human-readable data to my MVC View but I want the database to save the encrypted version and likewise when reading from the database. I need to have 2 pairs of getters and setters!

The solution is pretty easy. Create two properties. Mark one as NotMapped and use this for display, including encrypting/decrypting the human-readable data into a member variable and then have another property which is mapped to a column in the database but which is not displayed in the view. Something like this:

private string _code;   // Encrypted version of the code

        [NotMapped]
        [Display(Name = "Product Code")]
        [MaxLength(12)]
        [Required]
        public string Code 
        {
            get 
            { 
                if (_code == null) 
                    return null; 
                else return Owasp.Esapi.Esapi.Encryptor.Decrypt(_code); 
            }
            set 
            { 
                _code = Owasp.Esapi.Esapi.Encryptor.Encrypt(value.ToLower().Trim());
            }
        }

        [Column("code")]
        public string EncryptedCode
        {
            get { return _code; }
            set { _code = value; }
        }

Post a Comment