Richthofen
Richthofen

Reputation: 2086

Entity Framework Code First, nonempty setter or getter?

I am working with an EF Code First project, and all is well. I have a simple Class, Customer. In my Customer Class I have a field I want to encrypt (Yes, I know I can encrypt at the DB level but requirements dictate I encrypt at the Domain/Code level), so I am hoping that I can do something like the following:

public class Customer
{
    public int CustomerID { get; set; }      
    public string FieldToEncrypt { get; set { _FieldToEncrypt = MyEncryptionFunction.Encrypt(); } }
}

However, I assume that if the setter has a definition, entity framework code first may ignore that property when generating the schema. So my question is, is there a way to do EF Code First with provided getters/setters, or should I move this functionality into a constructor? Should I override one of the methods/events that happens when the Context is saving, instead?

EDIT ********************

As a note, I am using DataService to transmit the data over an OData protocol service. This automatically generates insert/update/select methods. Some of the suggestions require creating a second property, but the DataService class does not seem to pass through NotMapped properties. This throws a bit of a kink into my earlier question.

Upvotes: 9

Views: 4643

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

public class Customer 
{
    public int CustomerID { get; set; }        
    public string EncryptedField { get; private set; }

    [NotMapped]
    public string Field
    {
        get { return MyEncryptionFunction.Decrypt(EncryptedField); }
        set { EncryptedField = MyEncryptionFunction.Encrypt(value); }
    } 
}

Upvotes: 5

Related Questions