Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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; }
}
like image 538
K.Z Avatar asked Jan 20 '15 15:01

K.Z


People also ask

How do you handle column names with space?

DML SQL query with space in a column name When we run INSERT, UPDATE, and DELETE statements, we must use a square bracket or double quotes to handle the column name with space.

Can a column name have spaces?

Column names can contain any valid characters (for example, spaces). If column names contain any characters except letters, numbers, and underscores, the name must be delimited by enclosing it in back quotes (`).

How can I get SQL query results without column names?

To display the results of a query without column headings, use the WITHOUT HEADINGS keywords.


2 Answers

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; }
}
like image 64
Paul Aldred-Bann Avatar answered Oct 19 '22 08:10

Paul Aldred-Bann


Use the ColumnAttribute to set the name:

 [Column(Name="Level Description")]
 public string LevelDescription { get; set; }
like image 37
stuartd Avatar answered Oct 19 '22 09:10

stuartd