这个EF的东西对我来说似乎不是一个简单的路线初学者:(。我有以下SQL,它提供了20条记录:
SELECT
Suppliers.SupplierName,
srma.Id,
srma.CreatedOn,
srmaStatuses.StatusName,
srma.Status,
srma.PONumber,
srma.PONumber,
PurchaseOrders.PODate,
PurchaseOrders.suppliersOrderNumber
FROM
SRMAs srma
join srmastatuses on srma.status = srmastatuses.id
JOIN PurchaseOrders on SRMA.PONumber = PurchaseOrders.PONumber
JOIN Suppliers on Suppliers.SupplierID = PurchaseOrders.SupplierID
WHERE
srma.Status in (0,1)
AND(PurchaseOrders.suppliersOrderNumber LIKE '%2002%' OR srma.PONumber = '2002')
我制作了以下LINQ版本,但没有返回任何记录:
var searchQuery = collection["query"].Trim();
DBContext_Model db = new DBContext_Model();
int[] ids = new int[] { 0, 1 };
//LINQ way to JOIN tables
var srmas = (
from SRMAs in db.SRMAs
join SRMAStatus in db.SRMAStatus on SRMAs.Id equals SRMAStatus.Id
join PurchaseOrders in db.PurchaseOrders on SRMAs.PONumber equals PurchaseOrders.PONumber
join Suppliers in db.Suppliers on PurchaseOrders.SupplierID equals Suppliers.SupplierID
join SRMADetails in db.SRMADetails on SRMAs.Id equals SRMADetails.SRMAId
where
(
ids.Contains(SRMAs.Status)
&&
(
searchQuery.Contains(PurchaseOrders.suppliersOrderNumber)
||
searchQuery.Contains(SqlFunctions.StringConvert((decimal)SRMAs.PONumber))
)
)
select new
{
SRMAs.Status,SRMAs.Id,
SRMAs.PONumber,
SRMAs.CreatedOn,
Suppliers.SupplierName,
SRMAStatus.StatusName,
PurchaseOrders.PODate,
PurchaseOrders.suppliersOrderNumber
}).ToList();
如果我删除这部分仍然只返回4记录虽然它应该做20。
&&
(
searchQuery.Contains(PurchaseOrders.suppliersOrderNumber)
||
searchQuery.Contains(SqlFunctions.StringConvert((decimal)SRMAs.PONumber))
)
是否可以使用LINQ而不是搞乱我的生活?
答案 0 :(得分:1)
1。 on
子句应将FK与PK进行比较,您在将SRMA
加入SRMAStatus
时将PK与PK进行比较。将SRMAs.Id equals SRMAStatus.Id
更改为SRMAs.StatusId equals SRMAStatus.Id
。
2. 删除此部分join SRMADetails in db.SRMADetails on SRMAs.Id equals SRMADetails.SRMAId
,因为sql查询没有到SRMADetails的join子句。
3。目前您的搜索查询会生成以下内容:
CAST(CHARINDEX(PurchaseOrders.suppliersOrderNumber, '2002') AS int) > 0
or
CAST(CHARINDEX(cast(SRMAs.PONumber as varchar(max)), '2002') AS int) > 0
它应该在哪里:
PurchaseOrders.suppliersOrderNumber.Contains(searchQuery)
||
SqlFunctions.StringConvert((decimal)SRMAs.PONumber).Contains(searchQuery)
这样它就会产生类似的东西:
PurchaseOrders.suppliersOrderNumber LIKE '%2002%'
||
srma.PONumber LIKE '%2002%'