C# MVC 中的 Linq 右外连接查询

Linq Right Outer Join Query in the C# MVC

我想查询显示公司内外的车辆。下面的查询显示了外面的车辆和没有跟踪记录的车辆。看不到里面有跟踪记录的车辆

如何通过单个查询完成此操作?

表格

记录

查询

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();

我想要的结果

谢谢,亲切的问候。

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

中的问题

示例:

1.If 你需要 WHERE 条件 try-

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.Without 条件

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();