Convert value when mapping

As others have pointed out you need two properties, but you may be interested to know that you can make one of the properties private and still map it to the database:

    private string isActive { get; set; }

    [System.ComponentModel.DataAnnotations.Schema.NotMapped]
    public bool IsActive
    {
        get { return isActive == "Y"; }
        set { isActive = value ? "Y" : "N"; }
    }

If you are using EF6 you can use a custom convention in the OnModelCreating method to map the private property

modelBuilder.Types().Configure(c =>
{
    //NB the syntax used here will do this for all entities with a 
    //private isActive property
    var properties = c.ClrType.GetProperties(BindingFlags.NonPublic 
                                             | BindingFlags.Instance)
                              .Where(p => p.Name == "isActive");
    foreach (var p in properties)
        c.Property(p).HasColumnName("IsActive");
});

References:

Mapping private properties using custom conventions

Mapping private properties without custom conventions (before EF6)

Edit:

Here’s another way of identifying the private properties that should be mapped to the database:

First add the column attribute to the private property:

[System.ComponentModel.DataAnnotations.Schema.Column]
private string isActive { get; set; }

Then use the presence of that attribute to identify private properties in your OnModelCreating method:

modelBuilder.Types().Configure(c =>
{
    var properties = c.ClrType
        .GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
        .Where(propInfo => 
           propInfo.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0);

    foreach (var p in properties)
        c.Property(p).HasColumnName(p.Name);
});

Reference: Mapping a private property with entity framework

Leave a Comment