【问题标题】:how to select columns from two table with where using linq如何使用 linq 从两个表中选择列
【发布时间】:2019-07-31 11:28:55
【问题描述】:

我有三张桌子:

service_group
{
    id,
    title
}

service
{
    id,
    title,
    group_id
}

service_rate
{
    id,
    title,
    service_id,
    price,
    date
}

我有一个group_service 的组合框,用户必须选择一个然后打开一个表单,用户可以从service_rate 列表中进行选择。 service_rate 列表包括所有servic_rateservice_idservice.idselected service_group_id

如果我的英语说得不好,请见谅。

我的代码:

var list = (
  from p in db.Tbl_Services
  where p.Service_Group_ID == _service_group_id
  select new {
    p.ID,
    p.Title,
    p.Tbl_Services_Rate.Where(m = > m.Service_ID == p.ID).Last().Price,
    p.Tbl_Services_Rate.Where(m = > m.Service_ID == p.ID).Last().date
}).ToList();

但似乎不起作用。

【问题讨论】:

  • 问题是什么?
  • 我的代码不起作用。我想要一个这样的 linq 查询
  • 你想要一个 linq 查询来做什么?
  • 我想要一个与此 sql 查询等效的 linq 查询:select * from Tbl_Services_Rate where Service_ID in (select ID from Tbl_Services where Service_Group_ID = 2)
  • 您想要所选服务组下的所有服务的 service_rate 吗?

标签: c# entity-framework linq lambda linq-to-sql


【解决方案1】:

你可以这样做:

var list = db.Tbl_Services_Rate
    .Where(x=>x.service.group_id  == _service_group_id && x.service_id != null && x.service_id != "")
    .GroupBy(x=>x.service_id)
    .Select(x=>x.OrderByDescending(y=>y.id).FirstOrDefault())
    .ToList();

Null 检查是因为您将删除那些可能包含 service_id 为 null 或空的记录,因为您必须使用此 id 进行检查。

【讨论】:

    【解决方案2】:

    您假设首先从 Tbl_Service 中选择所有 ID 并存储在列表/数组中。然后在第二个查询中使用 Contains 过滤 ID。试试下面的代码。

    var tblService = (from x in Tbl_Services where x.Service_Group_ID == "2" select x.ID).ToList();
    
    var Tbl_Services_Rate = from y in Tbl_Services where tblService.Contains(y.Service_ID) select y;
    

    【讨论】:

      【解决方案3】:

      请尝试以下 LINQ 查询,

      from sr in  service_rate
                     join s in service on sr.service_id equals s.id
                     join sg in service_group on s.group_id  equals sg.id
                     where sg.id==2
                     select new 
          {sr.id,
              sr.title,
              sr.service_id,
              sr.price,
              sr.date}
      

      【讨论】:

        【解决方案4】:
        var list = (from MM in service_rate join TL in service on MM.service_id equals TL.id
                                   join Em in service_group on TL.group_id equals Em.id
                                   where TL.group_id = 2 select new {
                                       MM.id,
                                       MM.title,
                                       MM.service_id,
                                       MM.price,
                                       MM.date,
                                   }).ToList();
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多