Mapping to Private Properties with Code First

By default Code First will just include public properties in your model, but there may be times that you want to include private properties. Arthur Vickers wrote a great detailed post on working with private properties so I’m just going to cover enough to get you started in this post.

For example, the following model includes a Person entity with FirstName and LastName properties that we don’t want to expose to developers using the class – so we’ve marked them as private. However we do want Entity Framework to persist these properties to the database.

public class SampleContext : DbContext
{
    public DbSet<People> { get; set; }
}

public class Person
{
    public int PersonId { get; set; }
    private string FirstName { get; set; }
    private string LastName { get; set; }

    public void SetName(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    public string GetName()
    {
        return LastName + ", " + LastName;
    }
}

If we used the classes as-is, Code First would only include the key column in the model.

JustKey

The Solution

The solution is to use the Property method from the Code First fluent API to let Code First know that these two properties should be included in the model. However, we can’t put this call in the OnModelCreating method of our context because the properties can’t be accessed from there because they are private.

The solution is to use an entity configuration class that is nested inside our entity class, and therefore has access to the private properties.

public class Person
{
    public int PersonId { get; set; }
    private string FirstName { get; set; }
    private string LastName { get; set; }

    public void SetName(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    public string GetName()
    {
        return LastName + ", " + LastName;
    }

    public class PersonConfiguration : EntityTypeConfiguration&lt;Person&gt;
    {
        public PersonConfiguration()
        {
            Property(p => p.FirstName);
            Property(p => p.LastName);
        }
    }
}

We then register this configuration class in the OnModelCreating method of our context.

public class SampleContext : DbContext
{
    public DbSet<Person> People { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new Person.PersonConfiguration());
    }
}

Code First will now include the properties in our model and include the corresponding columns in the database.

WithNames

Advertisements