我使用Linqer将SQL转换为LinQ,但结果不一样 我的SQL查询:
Select ChuyenNganh.ChuyenNganhID,ChuyenNganh.TenChuyenNganh,SoLuong= count(BaiBao.ChuyenNganhID )
from BaiBao right join ChuyenNganh on ChuyenNganh.ChuyenNganhID = BaiBao.ChuyenNganhID
group by ChuyenNganh.ChuyenNganhID, ChuyenNganh.TenChuyenNganh
转换为Linq
var queryChuyenNganh = from t in myPhanLoaiTaiLieuDataContext.ChuyenNganhs
join t0 in myPhanLoaiTaiLieuDataContext.BaiBaos on new { ChuyenNganhID = t.ChuyenNganhID } equals new { ChuyenNganhID = Convert.ToInt32(t0.ChuyenNganhID) } into t0_join
from t0 in t0_join.DefaultIfEmpty()
group t by new
{
t.ChuyenNganhID,
t.TenChuyenNganh
} into g
select new
{
ChuyenNganhID = (System.Int32)g.Key.ChuyenNganhID,
g.Key.TenChuyenNganh,
SoLuong =(Int32)g.Count()
};
结果:
LINQ的
SQL
谁可以帮我解决?
答案 0 :(得分:1)
很可能SQL查询可以在没有//page.Height = XUnit.FromMillimeter(baseY + 10).Point;
double height = XUnit.FromMillimeter(baseY + 10).Point;
page.CropBox = new PdfRectangle(new XPoint(0, page.Height - height),
new XSize(page.Width, height));
的LINQ中重写,而是简单的LINQ group by
。
但转换的主要问题是SQL GroupJoin
不计算COUNT(expr)
值,并且没有直接的LINQ等效值,因此条件NULL
或Count
需要(我个人更喜欢后者,因为通常它转换为更好的SQL)。
因此,您查询所需的最小更改是
Sum
至group t by new
和group t0 by new
到SoLuong =(Int32)g.Count()
P.S。正如开头所提到的,我将尝试以下LINQ查询:
SoLuong = g.Sum(t0 => t0 != null ? 1 : 0)
答案 1 :(得分:0)
区别在于SQL在BaiBao.ChuyenNganhID
(外连接表中的一列)中计算非空值,而LINQ计算所有记录。
您还需要使LINQ计数非空值:
var queryChuyenNganh = from t in myPhanLoaiTaiLieuDataContext.ChuyenNganhs
join t0 in myPhanLoaiTaiLieuDataContext.BaiBaos
on new { t.ChuyenNganhID } equals new { ChuyenNganhID = Convert.ToInt32(t0.ChuyenNganhID) } into t0_join
from t0 in t0_join.DefaultIfEmpty()
group new {T=t, NonNull=t0.ChuyenNganhID != null} by new
{
t.T.ChuyenNganhID,
t.T.TenChuyenNganh
} into g
select new
{
ChuyenNganhID = (System.Int32)g.Key.ChuyenNganhID,
g.Key.TenChuyenNganh,
SoLuong =(Int32)g.Count(x => x.NonNull)
};