Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 954
Richthofen Avatar asked Feb 04 '13 20:02

Richthofen


People also ask

What is code first approach in Entity Framework?

In the ASP.NET MVC framework, the code-first approach is a development model where you first write the code that creates the data access layer, then you write the code that creates the controllers and views. In the code-first approach, you create a model, which is a class that represents the data in the application.

Can we use setter without getter?

The interface specifies that the property should at least have a public setter. The definition and accessibility of the getter is left to the implementing class. So if the interface contract only needs to write, get can be left open.

Why use JavaScript setter?

In JavaScript, a setter can be used to execute a function whenever a specified property is attempted to be changed. Setters are most often used in conjunction with getters to create a type of pseudo-property. It is not possible to simultaneously have a setter on a property that holds an actual value.


1 Answers

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); }
    } 
}
like image 103
Sergey Berezovskiy Avatar answered Oct 21 '22 16:10

Sergey Berezovskiy