Reputation: 1977
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.
Upvotes: 2
Views: 1677
Reputation: 4974
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.
Upvotes: 1