I have a database with a table that contains Name and CompanyName. They are mutually exclusive (either field is null). Using LINQ to SQL, I’m trying to order these two “into” each other (but not in-memory, I would like this done by SQL Server 2008) so that I can get a single column “DisplayName” which will do this:
Record Name CompanyName
1 Smith NULL
2 Fields NULL
3 NULL Microsoft
4 Zian NULL
5 NULL Gibbons
My output should be
Record DisplayName
2 Fields
5 Gibbons
3 Microsoft
1 Smith
4 Zian
Note how the output is ordered across both source columns. This needs to support pagination (skip & take). Any idea how to do this?
Thanks to spender I have this now:
db
.Table
.Where(t=>t.Year>1990)
.Select(t=>new{t.Record,DisplayName=t.Name??t.CompanyName})
.OrderBy(t.DisplayName);
The remaining problem is: How can I still return only the original domain objects? The anonymous type introduced in above query now throws errors that the return type is wrong (which has to stay (IQueryable)). Almost there?!.. Basically I need to find a way to assign the “DisplayName” value sorted for to the original object during the query.
EDIT:
Would create SQL similar to:
This looks like it fulfills your requirements. You could happily tack Skip and Take to the end of this statement to support pagination.
To account for Year (as per comment):
You last requirement would be as simple as writing a new class to encapsulate the result:
Then the query would become:
However, I am starting to think that if you were to create a view of the SQL query:
and then to drag this view onto your Dbml surface, you might get better mileage.
EDIT:
If you can, the optimal approach would be to alter the source table as follows, so that DisplayName becomes a computed column at source.
I finally grok your question (I didn’t realise DisplayName was only for ordering purposes, and not required to be maintained). Here’s your query:
TADA!