使用外键值进行排序的简单方法?

发布于 2024-09-01 08:15:48 字数 273 浏览 4 评论 0原文

免责声明:我最近同时跳到了 C# 2008 和 SubSonic 3 (3.0.0.4)。我过去没有使用 Linq 做过很多事情。

有没有一种简单的方法可以使用外键显示值进行排序,而不是使用 FK Id(数字)?

我在 ActiveRecord.tt 中添加了一个新的 Find 方法,以帮助根据字符串字段名称进行排序,但经过一些测试后,我意识到即使它应该按预期工作,我根本不处理外键字段(他们只是按其价值排序)。

即使我需要改变访问数据的方式,在项目中也已经足够早了。只是寻找建议。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

没︽人懂的悲伤 2024-09-08 08:15:48

在这种情况下,LINQ 是你的朋友,你只需连接两个对象,然后按外来对象的属性进行排序:

var primaryObjectsSorted =
  from primaryObjects in PrimaryObject.All()
  join foreignObjects in ForeignObject.All() 
    on primaryObjects.ForeignId equals foreignObjects.Id
  orderby foreignObjects.PropertyYouWantToSortOn
  select primaryObjects;

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;
怎樣才叫好 2024-09-08 08:15:48

因此,您的表 A 将表 B 的 id 作为外键,并且您希望通过表 B 的 DisplayName 列而不是表 B 的 id 对表 A 进行排序?

实现这一点的唯一方法是通过连接。

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

在 SubSonic2 中,您可以做到这一点,并且如果您使用 DB.Select(...).ExecuteCollection() 方法,仍然能够更新您的记录。
我认为 subsonic3 也应该可以实现这一点。

但是,如果您不使用外键并且显示名称是唯一的,则应该使用该值作为外键。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文