Brian J Brian J - 2 months ago 14
C# Question

How to read back a column name with spaces using linq?

I'm reading back a query using a linq Select where some of the SQL Server database column names include blank spaces in the column name.

Reading back the first column

ID
works fine and I can see the query being returned. But when I add in the second column with spaces taken from the DB schema,
[Contact Email Name]
it throws an
invalid column name exception
:

enter image description here

I did try as suggested here adding the
DataMemberAttribute
to the property name, but the same exception is thrown:

public class Status
{

[Key]
public int ID { get; set; }

[DataMember(Name = "Contact Email Name")]
public string Contact_Email_Name { get; set; }


}


Question:

How can you read back a column name with spaces using linq?

This is the linq statement where the column values are read back:

var query_all = from n in db3.Statuses
select new
{
ID = n.ID,
Contact_Email_Name = n.Contact_Email_Name,

};

Answer

Try using the Column attribute instead of DataMember

public class Status
{

    [Key]
    public int ID { get; set; }

    [Column("Contact Email Name")]
    public string Contact_Email_Name { get; set; }


}