2

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.

furier
  • 1,934
  • 1
  • 21
  • 39
  • 1
    Make `MyColumnAsInt` private and map it using a solution from http://stackoverflow.com/a/21686896 – haim770 May 11 '15 at 07:11

1 Answers1

1

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.

Manuel Schweigert
  • 4,884
  • 4
  • 20
  • 32
  • That's an interesting idea, but I think the solution @haim770 linked to is more correct tho I cant fathom why Microsoft hasn't made an attribute for this... Anyways thanks. – furier May 11 '15 at 07:19
  • I see, my annotation hides the property where the linked post actually makes it private. In any case, you can always head over to the EF user voice site and check if there's a request for this, and if not, request it: http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions – Manuel Schweigert May 11 '15 at 09:26
  • 1
    looks like they will do it in EF7: http://data.uservoice.com/forums/72025-entity-framework-feature-suggestions/suggestions/2639292-simple-type-mapping-or-mapped-type-conversion-supp – Manuel Schweigert May 11 '15 at 09:27