我有以下返回SQL子查询的方法。通过该方法的返回,我详细说明了主要查询。
但现在我需要使用 LINQ 查询来执行此操作。
我该怎么做?
Public void AvailableStock()
{
string query = "Select prod.ID, prod.Name, ";
query += AvailableStockQuery("prod.ID") + " as AvailableStock ";
query += " From TAB_Products prod ";
}
Public string AvailableStockQuery(string ProductAlias = "prod.ID")
{
string query = "((Select Sum(est.Quantity) " +
" From ProductStock est " +
" Where est.ProductID = " + ProductAlias +
" ) " +
" - (Select Sum(it.Quantity) " +
" From OrderItens it " +
" Where it.ProductID = " + ProductAlias +
")" +
") ";
return query;
}
但是,您甚至不需要这里的子查询。您只需将 ProductStock 和 OrderItens 表连接到TAB_Products表,然后按 prod.ID 分组,然后根本不需要子查询。可能性能也更好。并且更容易将其转换为 EF,因为没有子查询。
像这样:
SELECT prod.ID, FIRST(prod.Name), (SUM(est.Quantity) - Sum(it.Quantity)) AS AvailableStock
From TAB_Products prod
LEFT JOIN ProductStock est ON est.ProductID = prod.ID
LEFT JOIN OrderItens it ON it.ProductID = prod.ID
GROUP BY prod.ID
但是,如果你愿意,你也可以做子查询,这里有一个例子:https://learn.microsoft.com/en-us/dotnet/csharp/linq/perform-a-subquery-on-a-grouping-operation