views:

64

answers:

2

Disclaimer: I jumped to C# 2008 recently and SubSonic 3 (3.0.0.4) at the same time. I haven't used Linq for much of anything in the past.

Is there an easy way to use the foreign key display value for sorting, rather than the FK Id (which is numeric)?

I've added a new Find method in my ActiveRecord.tt to help with sorting based on a string field name but after doing some testing I realized that even though its working as it should be, I am not handling foreign key fields at all (they are just sorting by their value).

Even if I need to change how I am accessing the data it is early enough in the project to do that. Just looking for suggestions.

A: 

So you have table A which has id of table B as a foreign key and you want to sort table A by the DisplayName column of table B rather than the id of table B?

The only way to achive this is by a join.

SELECT tableA.* FROM tableA INNLER JOIN tableB ORDER BY tableB.DisplayName

In SubSonic2 you can do that, and still be able to update your records if you use the DB.Select(...).ExecuteCollection() method. I think this should be possible with subsonic3, too.

Howevery, if you don't use the foreign key and the display name is unique, you should just use this value as your foreign key.

SchlaWiener
In my case, I do not need to edit the record. I am using this to populate a grid. The grid is supposed to support paging and sorting by clicked field (first asc, then desc on second click on the same field).Your suggesting to link to the display field rather than the Id would work for me in most cases, although there will be cases where it wont. I'm going to take a look at all my options and do some more research before I decide the best way to go.
Brian Rizzo
+1  A: 

LINQ is your friend in this situation, you just need to join your two objects and then sort by the property from your foreign object:

var primaryObjectsSorted =
  from primaryObjects in PrimaryObject.All()
  join foreignObjects in ForeignObject.All() 
    on primaryObjects.ForeignId equals foreignObjects.Id
  orderby foreignObjects.PropertyYouWantToSortOn
  select primaryObjects;
Adam
Adam, I worked with something like that last night, my problem is that my sort field and order are dynamic. This is why I worked out a custom Find method in the activerecord.tt. I guess I could do the same thing with LINQ code, but thinking more about it I think my DB design may be more of an issue than this. My FK could be (as SchlaWiener said) the display field which is also unique in this case. However I'm sure at some point I'll run into a case where I need more and LINQ seems to handle 99% of what I need. I need to think this through more thoroughly, I believe.
Brian Rizzo