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.
我使用实体框架6(EF6),我想映射一个类型为int的列,其值只有0或1到我的实体上的bool类型的属性。
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.
我想这样做,而不需要为同一列提供两个属性,方法是使用未使用映射在其get'er和set'er中的属性映射的属性进行映射。
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?
但我似乎无法弄清楚的是,如果可以像NHibernate那样单独使用Attributes吗?如果没有,为什么?为什么没有实施?
Its a hassle to have two properties for the same thing when both of them need to be public.
当两者都需要公开时,为同一件事物提供两个属性是一件麻烦事。
1 个解决方案
#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.
这样,如果通过intellisense浏览类,则只能看到具有正确名称的boolean属性,而back3属性的隐藏属性是隐藏的,并使用Column属性中的名称来获取db中的属性映射。
#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.
这样,如果通过intellisense浏览类,则只能看到具有正确名称的boolean属性,而back3属性的隐藏属性是隐藏的,并使用Column属性中的名称来获取db中的属性映射。