【问题标题】:Linq query to select data from table and join 2 tablesLinq查询从表中选择数据并连接2个表
【发布时间】:2014-06-30 07:54:48
【问题描述】:

我正在尝试 select 一个表中的所有内容,然后与另外两个表进行连接,我只需要其中的一些列。最终列表将填充到DevExpress GridControl。我从中获取数据的主表有这些列:

Id | ScheduleId | AccountId | Description

我可以轻松地从该表中选择所有内容并返回。这是我的清单:

public IList<StatusDescription> getStatusDescription()
{
    var listOfItems = from e in context.StatusDescription select e;
    return listOfItems.ToList<StatusDescription>();
}

另外两个表是 Schedules 和 Accounts,它们如下所示:

Id | ScheduleName | DateFrom | DateTo

Id | AccountName | AccountCode

我想加入Schedule 表中的DateFromDateTo 以及Account 表中的AccountCode。是否有可能将所有这些都放入一个列表中。稍后我可以轻松地将其绑定到GridControl

【问题讨论】:

标签: c# linq


【解决方案1】:
var listOfItems = from e in context.StatusDescription
                  join s in context.Schedules on e.ScheduleId equals s.Id
                  join a in context.Accounts on e.AccountId equals a.Id
                  select new 
                  {
                      Description = e.Description,
                      ScheduleStart = s.DateFrom,
                      ScheduleEnd = s.DateTo,
                      AccountCode = a.AccountCode
                  }

【讨论】:

  • 我接受了答案,因为它是问题的解决方案。但是你知道返回类型应该是什么吗,因为试图返回IList&lt;StatusDescription&gt; 会报错(我明白为什么会这样)。
  • @Ivo 在示例中,返回类型是匿名对象,如果您需要返回特定类型,那么您需要创建一个容纳这些特定字段select new QueryType { ... } 的类型。你不能指望StatusDescription,因为它没有ScheduleStart/ScheduleEnd等属性。
  • 感谢您的评论,我希望避免创建新课程,但现在已经完成了。
【解决方案2】:

var Query = from p in context.StatusDescription select new { p.Id, p.Description, p.Schedule.DateFrom, p.Schedule.DateTo, p.Account.AccountCode };

希望对你有帮助

【讨论】:

  • 是的,这是一个简单的选择,这意味着在这种情况下我们不需要“加入”:)
猜你喜欢
  • 1970-01-01
  • 2017-11-04
  • 2023-03-07
  • 2022-01-19
  • 1970-01-01
  • 2023-03-20
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
相关资源
最近更新 更多