EF6 Map column of type int to entity property type bool

entity-framework entity-framework-6

Question

I use Entity Framework 6 (EF6), and I want to map a table with a column of type int which only have values 0 or 1 to a property of type bool on my entity.

I would like to do so without the need for having two properties for the same column by having a property that is not mapped using the property that is mapped in its get'er and set'er like this.

public class MyEntity 
{
    ...

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

    public int MyColumnAsInt { get; set; }

    ...
}

But what I can not seem to figure out is if this can be done with Attributes alone like in NHibernate? and if not, why? Why hasn't it been implemented?

Its a hassle to have two properties for the same thing when both of them need to be public.

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

Popular Answer

I don't think there is a way to do this better, but you can do some things to make it look alright:

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; }

    ...
}

This way, if you browse the class through intellisense, you will only see the boolean property with the proper name, while the backing property is hidden from intellisense and uses the name from the Column attribute to get the property-mapping in the db.

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