【问题标题】:Sorting issue with LINQ query and join using tables from different databases使用来自不同数据库的表的 LINQ 查询和连接的排序问题
【发布时间】:2013-07-03 18:43:36
【问题描述】:

我在编写 LINQ 查询时遇到问题。 场景如下:

我有 2 个数据库:A 和 B 在数据库 A 中:我有一个 tableX,其中包含以下字段:员工 ID、姓名、地址、电话、...、活动

在数据库 B 中:我有一个 tableY,其中包含以下字段:Employee ID、Visible、Order

Y表的记录数小于等于X表的记录数。

基本上,我需要从表 X 中提取属性“可见”(在表 Y 中)设置为 True 并希望使用“订单”属性对它们进行排序的员工记录。

这是我目前所拥有的:

ADataContext dbA = new ADataContext();
BDataContext dbB = new BDataContext();

//Get the list of records from tableY where 'Visbile' is set to True
var List  = dbB.tableY 
                     .Where(x => x.Visible == true).OrderBy(x => x.Order)
                     .ToList();

 //Extract the list of employee IDs
 IEnumerable<int> ids = List.Select(x => x.EmployeeID).Distinct();


var employees = dbA.tableX
                    .Where(x => ids.Contains(x.EmployeeID) && x.Active == true)
                    .ToList();

我能够获得正确的员工列表,但无法弄清楚如何在 tableX 上应用排序顺序(存在于 tableY 中) 目前,无论 tableY 中指定的顺序如何,从 tableX 返回的记录都会按照它们在表中输入的顺序进行排序(从最旧到最近)。

关于如何修复我的查询的任何想法。

谢谢,

【问题讨论】:

    标签: linq sorting join linq-to-entities


    【解决方案1】:

    我已将其全部重写为单个查询:

    var employees =
      from x in dbA.tableX
      where x.Active
      from y in dbB.tableY
      where x.EmployeeID == y.EmployeeID
      orderby y.Order
      select x;
    

    【讨论】:

    • 感谢您的快速回复!我尝试了您的建议,但“.OrderBy(x => x.Order)”语句不起作用,因为 tableX 中未定义“Order”列:(
    • 我已将上面的示例更新为使用单个联接。首先,您选择 TableX 的条目,过滤掉所有不活动的条目。然后您选择 TableY 的条目并将它们与它们的 X 对应项进行匹配。最后,您订购并返回 X 值。
    猜你喜欢
    • 2015-07-31
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 2011-06-21
    • 2015-11-04
    • 1970-01-01
    • 2021-01-12
    • 2018-02-06
    相关资源
    最近更新 更多