Reputation: 1402
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
Upvotes: 1
Views: 933
Reputation: 18746
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
Upvotes: 0
Reputation: 1502816
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.
Upvotes: 3
Reputation: 755269
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 %
Upvotes: 1
Reputation: 1777
In LINQ you still have to follow the rules of variable naming which does not allow spaces or % signs.
Upvotes: 3
Reputation: 12975
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.
Upvotes: 0