How to map a column name with spaces in it to a POCO property?

a 夏天 提交于 2021-01-18 05:49:02

问题


I am working on database table which has a column name with a space in it, for example "Level Description".

I cannot change the column name. Now I have an Entity Framework model class for this table and the compiler is complaining about this property, because property names can't contain spaces!

How can I define the column with space in my class?

[Table("StudyLevel")]
public class StudyLevelModel
{
    [Key]
    public byte StudyLevelID { get; set; } 

    // How to map this to the column "Level Description"?
    public string Level Description { get; set; }

    public string SLevelType { get; set; }
    public Nullable<bool> IsActive { get; set; }
    public string ESID { get; set; }
    public string RID { get; set; }
    public byte LevelSearchGroup { get; set; }
}

回答1:


You don't have to have your model property names exactly matching your table column names; there is a [Column] attribute you can apply to map a property to the column:

[Table("StudyLevel")]
public class StudyLevelModel
{
    [Key]
    public byte StudyLevelID { get; set; } 
    [Column("Level Description")]
    public string LevelDescription { get; set; }
    public string SLevelType { get; set; }
    public Nullable<bool> IsActive { get; set; }
    public string ESID { get; set; }
    public string RID { get; set; }
    public byte LevelSearchGroup { get; set; }
}



回答2:


Use the ColumnAttribute to set the name:

 [Column(Name="Level Description")]
 public string LevelDescription { get; set; }


来源:https://stackoverflow.com/questions/28049620/how-to-map-a-column-name-with-spaces-in-it-to-a-poco-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!