【问题标题】:Linq Right Outer Join Query in the C# MVCC# MVC 中的 Linq 右外连接查询
【发布时间】:2020-03-09 08:45:33
【问题描述】:

我想通过查询显示公司内外的车辆。下面的查询显示了外面的车辆和没有记录的车辆。车内和有跟踪记录的车辆不可见。

如何通过单个查询来完成?

表格

记录

查询

var VehiclesStatus = (from veh in db.Sec_Vehicle
                      join tracing in db.Sec_Tracing on veh.Id equals tracing.CarId into trc
                      from trace in trc.DefaultIfEmpty()
                      where trace.EntryDate == null || trace == null
                      orderby veh.Brand
                      select new VehicleStatus
                      {
                            Brand = veh.Brand,
                            Driver = trace != null ? trace.DriverName : string.Empty,
                            ReleaseDate = trace != null ? trace.ReleaseDate.ToString("HH:mm") : "",
                            Status = trace != null ? "Vehicle Busy" : "Vehicle Available"
                      }).ToList();

我想要的结果

谢谢,亲切的问候。

【问题讨论】:

    标签: asp.net-mvc linq linq-to-sql


    【解决方案1】:

    您的查询看起来不错。只是 where 子句中的问题 (where trace.EntryDate == null || trace == null)。

    例子:

    1.如果需要WHERE条件试试-

    var VehiclesStatus = (from veh in db.Sec_Vehicle
                          join tracing in db.Sec_Tracing on veh.Id equals tracing.CarId into trc
                          from trace in trc.Where(f => f.EntryDate== null).DefaultIfEmpty()//use :f.EntryDate== null if you need which has no EntryDate OR f.EntryDate!= null if you need which has EntryDate
                          orderby veh.Brand
                          select new VehicleStatus
                          {
                                Brand = veh.Brand,
                                Driver = trace != null ? trace.DriverName : string.Empty,
                                ReleaseDate = trace != null ? trace.ReleaseDate.ToString("HH:mm") : "",
                                Status = trace != null ? "Vehicle Busy" : "Vehicle Available"
                          }).ToList();
    

    2.无条件

    var VehiclesStatus = (from veh in db.Sec_Vehicle
                          join tracing in db.Sec_Tracing on veh.Id equals tracing.CarId into trc
                          from trace in trc.DefaultIfEmpty()
                          orderby veh.Brand
                          select new VehicleStatus
                          {
                                Brand = veh.Brand,
                                Driver = trace != null ? trace.DriverName : string.Empty,
                                ReleaseDate = trace != null ? trace.ReleaseDate.ToString("HH:mm") : "",
                                Status = trace != null ? "Vehicle Busy" : "Vehicle Available"
                          }).ToList();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 2023-03-19
      相关资源
      最近更新 更多