EF6 Map column of type int to entity property type bool

entity-framework entity-framework-6

Question

I want to translate a table with an int column that only has the values 0 or 1 to a property of type bool on my entity using Entity Framework 6 (EF6).

By having a property that is not mapped use the property that is mapped in its get'er and set'er in this manner, I would like to accomplish this without the requirement for two properties for the same column.

public class MyEntity 
{
    ...

    [NotMapped]
    public bool MyColumnAsBool 
    {
        get { return MyColumnAsInt == 1; }
        set { MyColumnAsInt = value ? 1 : 0; }
    }

    public int MyColumnAsInt { get; set; }

    ...
}

But I'm having trouble figuring out if this can be accomplished using only attributes, like in NHibernate. if not, why not? Why hasn't it been put into action?

Having two properties for the same item when they both need to be accessible to the public is a nuisance.

1
2
5/11/2015 6:59:37 AM

Popular Answer

I don't believe there is a better method to do this, however there are some things you can do to make it look okay:

public class MyEntity 
{
    ...

    [NotMapped]
    public bool MyColumn 
    {
        get { return MyColumnAsInt == 1; }
        set { MyColumnAsInt = value ? 1 : 0; }
    }
    [Column("MyColumn")]
    [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
    public int MyColumnAsInt { get; set; }

    ...
}

The backing property is hidden from intellisense and utilizes the name from the class, so if you explore the class using intellisense, you will only see the boolean property with the proper name.Column attribute to obtain the database's property-mapping.

1
5/11/2015 7:07:31 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow