This EF thing does not seem an easy route for me as a beginner :(. I have following SQL which gives 20 records:
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')
I made the following LINQ version which is not returning any record:
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();
If I remove this part still it returns only 4 Record though it should do 20.
&&
(
searchQuery.Contains(PurchaseOrders.suppliersOrderNumber)
||
searchQuery.Contains(SqlFunctions.StringConvert((decimal)SRMAs.PONumber))
)
Is it possible to use LINQ rather than messing my life?
1. The on
clause should compare FK to PK, you were comparing PK to PK when joining SRMA
with SRMAStatus
. Change SRMAs.Id equals SRMAStatus.Id
to SRMAs.StatusId equals SRMAStatus.Id
.
2. Remove this part join SRMADetails in db.SRMADetails on SRMAs.Id equals SRMADetails.SRMAId
since the sql query doesn't have join clause to SRMADetails.
3. And the search query you had at the moment will generate something like:
CAST(CHARINDEX(PurchaseOrders.suppliersOrderNumber, '2002') AS int) > 0
or
CAST(CHARINDEX(cast(SRMAs.PONumber as varchar(max)), '2002') AS int) > 0
Where it should be:
PurchaseOrders.suppliersOrderNumber.Contains(searchQuery)
||
SqlFunctions.StringConvert((decimal)SRMAs.PONumber).Contains(searchQuery)
So that it generates something like:
PurchaseOrders.suppliersOrderNumber LIKE '%2002%'
||
srma.PONumber LIKE '%2002%'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.