Mapping to Private Properties with Code First

Posted on October 1, 2012. Filed under: Entity Framework, Visual Studio |

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

About these ads

Make a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

3 Responses to “Mapping to Private Properties with Code First”

RSS Feed for RoMiller.com Comments RSS Feed

If you declare your POCO in an extra project (“MyDataContractsProject”), you can also mark the properties as internal.
Then add the line “[assembly: InternalsVisibleTo(“MyEFDataAccessProject”)]” to the AssemblyInfo.cs.

If done so, the MyEFDataAccessProject has access to the internals of the “MyDataContractsProject”.

[…] while back I blogged about mapping to private properties with Code First. The approach shown in that post works with EF4.1 onwards but it requires you to explicitly […]

[…] while back I blogged about mapping to private properties with Code First. The approach shown in that post works with EF4.1 onwards but it requires you to explicitly […]


Where's The Comment Form?

    About

    Rowan works as a Program Manager for the ADO.NET Entity Framework team at Microsoft. He speaks at technical conferences and blogs at romiller.com. Rowan lives in Seattle, Washington with his wife Athalie. Prior to moving to the US he resided in the small state of Tasmania in Australia. Outside of technology Rowan's passions include snowboarding, mountain biking, horse riding, rock climbing and pretty much anything else that involves being active. The primary focus of his life, however, is to follow Jesus.

    RSS

    Subscribe Via RSS

    • Subscribe with Bloglines
    • Add your feed to Newsburst from CNET News.com
    • Subscribe in Google Reader
    • Add to My Yahoo!
    • Subscribe in NewsGator Online
    • The latest comments to all posts in RSS

    Meta

Liked it here?
Why not try sites on the blogroll...

Follow

Get every new post delivered to your Inbox.

Join 171 other followers

%d bloggers like this: