我有以下方法返回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;
}
答案 0 :(得分:0)
但是,您甚至不需要在这里进行子查询。您可以只将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://docs.microsoft.com/en-us/dotnet/csharp/linq/perform-a-subquery-on-a-grouping-operation