I'm trying to port the following piece of SQL to LINQ and I'm able to achieve what I need. But I believe there should be a better way to do it as the SQL generated as a CROSS JOIN, which is not performant.
SQL to port:
SELECT bu_code,
cust_no,
cust_name,
RANK () OVER (PARTITION BY bu_code, cust_no ORDER BY bank_id DESC) rnk
FROM customer;
LINQ to port the above SQL:
from cust in customer
group cust by new { cust.BuCode, cust.CustomerNumber } into grp
let MaxBankId = grp.Max(g => g.BankId)
from cust in grp
where cust.BankId == MaxBankId
select new
{
cust.BuCode,
cust.CustomerNumber,
cust.CustomerName
};
SQL generated by above query:
SELECT t3.BU_CODE, t3.CUST_NO, t3.CUST_NAME
FROM ( SELECT t2.BU_CODE AS "BuCode",
t2.CUST_NO AS "CustomerNumber",
MAX (t2.BANK_ID) AS C1
FROM CUSTOMER t2
WHERE ( :p0 <> 0)
AND (NOT (t2.BU_CODE IS NULL))
AND (t2.BU_CODE = :p1)
GROUP BY t2.BU_CODE, t2.CUST_NO) t1
CROSS JOIN CUSTOMER t3
WHERE (t3.BANK_ID = t1.C1)
AND (t1."BuCode" = t3.BU_CODE)
AND (t1."CustomerNumber" = t3.CUST_NO)
AND ( :p0 <> 0)
AND (NOT (t3.BU_CODE IS NULL))
AND (t3.BU_CODE = :p1)
PS: I'm working with Oracle 11g and Devart.
Thoughts on this?
Not all SQL constructions can be ported to LINQ. Not all LINQ queries are translated to SQL as efficiently as possible. In some situations, it is better to write a query in SQL and only materialize its result using an ORM. You're using LinqConnect, aren't you? Then you can use DataContext.Query (string query) method: https://www.devart.com/linqconnect/docs/?Devart.Data.Linq~Devart.Data.Linq.DataContext~Query.html .
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.