views:

176

answers:

5

In LINQ, I'd like to project different names than those from the database tables. "Friendly names" that I can use for column headers. Names that have "%" or possibly a " " (space). The query below won't compile.

Is something like that possible or am I stuck using the dreaded _ underscore for everything?

dim query = from p in ctx.SomeTable() _
    select ProductName = p.product_name, _
           [Expiration Date] = p.expiration_date,
           [% of sales] = p.pct_sales
A: 

For the select portion of your LINQ query, use something like

select new { MyNewProductName = p.product_name, MySillyColumnTitle = p.pct_sales }

and so forth. These properties will be automatically created for the IEnumerable collection that is returned by the query.

JoshJordan
That's C#, the questioner appears to be going for VB.Net
JaredPar
+3  A: 

In LINQ you still have to follow the rules of variable naming which does not allow spaces or % signs.

irperez
+1  A: 

It's certainly possible to project different names for the fields of the database by using the select clause.

Dim query = From p in ctx.SomeTable() _
  Select ProductName = p.product_name, ExpirationData = p.expiration_date

However the names that are chosen still must be valid VB identifiers. So that will preclude you from using a space or %

JaredPar
+3  A: 

You've still got to create valid variable names. Tying the display name to the variable name would be a very bad idea, IMO. There's absolutely no chance of i18n, which of course may not be an issue for you - but it's forming way too tight a bond between the UI and the data access code.

It would be far better to specify the column headers separately. That way you end up with sensible variable names which are easy to use from code, and column headers which aren't restricted by the rules or identifiers.

Jon Skeet
@Jon - +1 for separation of concerns, data model should be separate from presentation. I think you are referring to international character issues when you say i18n?
Maslow
A: 

If you make a class that sits between your Linq and your UI you can use

Imports System.ComponentModel

Public NotInheritable Class ModelSomeTable

'Help prevent accidental direct field access in the class
<EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)> _
private _pct_sales as decimal

'Components will know what to use for the heading
<Display("% of sales")> _
Public ReadOnly Property pct_sales() As decimal
    Get
        Return _pct_sales
    End Get
End Property

'code can see it, datagrids/datagridviews and other components won't
private _RowId as integer
<Browsable(false)> _
    Public ReadOnly Property RowId() As integer
    Get
        Return _RowId
    End Get
End Property

End Class
Maslow