c# - 具有 Linq 和默认值的多个左连接
问题描述
我正在尝试在 ac# .netcore 2.2 应用程序的 linq 中编写一个包含多个左连接的查询。我已经尝试在 linq 中编写查询,但它没有正确检索所有行。我要转换的查询如下。
select ISNULL(b.Id, '00000000-0000-0000-0000-000000000000') as 'Bat Id', p.Id as 'ProductId', p.RP, u.UnitName as 'UnitName', ISNULL(b.QTY,0) as 'BusQty', p.[Name] as 'Product Name'
from Products p left join Bat b
ON p.Id = b.ProductId
left join Units u on p.UOId = u.Id;
linq 我到目前为止
var allProducts = (from p in _db.Products
join s in _db.Bat on p.Id equals s.ProductId into ps
from s in ps.DefaultIfEmpty()
join u in _db.Units on p.UOId equals u.Id
select new
{
BatId = s.Id == null ? Guid.NewGuid() : s.Id,
RP = p.RP,
BusQty = s.QTY == null ? 0 : s.QTY,
ProductName = p.Name,
UnitName = u.UnitName,
ProductId = p.Id,
}).ToList();
解决方案
你错过DefaultIfEmpty()
了Units
,从而把它变成了一个内部连接
var allProducts = (
from p in _db.Products
join s in _db.Bat on p.Id equals s.ProductId into ps
from s in ps.DefaultIfEmpty()
join u in _db.Units on p.UOId equals u.Id into us
from u in us.DefaultIfEmpty()
select new
{
BatId = s.Id ?? Guid.NewGuid(),
RP = p.RP,
BusQty = s.QTY ?? 0,
ProductName = p.Name,
UnitName = u.UnitName,
ProductId = p.Id,
}).ToList();
推荐阅读
- android - 将片段添加到 BackStack 不断抛出错误
- jqgrid - Free JqGrid - 网格不刷新
- electron - 限制电子应用程序只能安装在 Windows 7 及更高版本上?
- c# - 反序列化 JSON - 如何反序列化这个 JSON?
- python - gdal.Open IndexError:列表索引超出范围
- mongodb - Mongodb删除集合字段中所有出现的字符串
- python - Geopy:OSError:[Errno 101] 网络无法访问
- java - 将布尔值更改为布尔值会在 MapStruct 中引发 noSuchMethodError
- javascript - 处理 promise 中的错误时返回成功
- angular - 组角6内的嵌套formarray