将SQL查询重写为LINQ。找不到错误

时间:2015-12-04 08:34:39

标签: c# sql-server entity-framework linq

这是一个SQL查询:

SELECT Website,VendorID,Name,LinkProduct,
            Link,Logo,Image,NameExtra as Industry,
            (SELECT [Percent] FROM Web_Promotion 
            WHERE Web_Promotion.VendorID=Web_Vendor.VendorID) 
            AS PercentOff  
            FROM Web_Vendor WHERE Active='1' AND 
            (VendorID IN (Select VendorID FROM Web_Promotion 
            WHERE VendorID<>'' AND Static='True' AND [Percent] <> '0' AND 
            ((Expires>=GETDATE()) OR (Expires IS NULL))) OR 
            VendorID IN (SELECT TOP 1 SC1 FROM NavItems 
            WHERE SC1=Web_Vendor.VendorID AND Promotion<>'' 
            AND ((PromotionStart<=GETDATE() AND PromotionEnd>=GETDATE()) 
            OR (PromotionStart<=GETDATE() AND PromotionEnd IS NULL))))
            ORDER BY NameExtra,Sequence 

我需要将它重写为LINQ。所以这是我的LINQ:

return await _db.Web_Vendor.
                    Where(x => !(x.WebPromotion.VendorID == string.Empty || x.WebPromotion.VendorID == null)
                    && x.WebPromotion.Static == true && x.WebPromotion.Percent != 0 &&
                    (x.WebPromotion.Expires >= DateTime.Now || x.WebPromotion.Expires == null)
                    ||
                    (_db.NavItems.Where(y => x.WebPromotion.VendorID == y.SC1
                        && !(y.Promotion == "" || y.Promotion == null)
                        && (y.PromotionStart <= DateTime.Now) && (y.PromotionEnd >= DateTime.Now || y.PromotionEnd == null))
                        .Select(g => g.SC1).Take(1).Contains(x.WebPromotion.VendorID)))
                    .Include(x => x.WebPromotion).Where(x => x.Active == true).OrderBy(x => x.NameExtra)
                    .ThenBy(x => x.Sequence).ToListAsync();
我花了大约三个,但找不到错误。原始SQL查询返回16行,但我的LINQ代码只返回13行。不幸的是,我只有一个导航属性(Web_Vendor&lt; - &gt; Web_Promotion)。我认为我的查询的第二部分出现错误:

||
                        (_db.NavItems.Where(y => x.WebPromotion.VendorID == y.SC1
                            && !(y.Promotion == "" || y.Promotion == null)
                            && (y.PromotionStart <= DateTime.Now) && (y.PromotionEnd >= DateTime.Now || y.PromotionEnd == null))
                            .Select(g => g.SC1).Take(1).Contains(x.WebPromotion.VendorID)))

任何专家都可以查看我的代码并帮助我吗? 正确的数据: http://prntscr.com/9a5xwu Linq数据(不正确)包含与正确相同的数据,而不是PercentOff为空的值。 主要问题是LINQ在这个地方生成内连接而不是左连接:http://prntscr.com/9a6stb

1 个答案:

答案 0 :(得分:0)

因为你说你的linq数据在PercentOff = null时错过了,所以我专注于那个

我猜你在Linq中的“PercentOff”是Percent属性,我看到你在你的位置:“x.WebPromotion.Percent!= 0”

这是一个可以为空的值,还是将null转换为默认属性类型,即0?

不能将null转换为0,然后查询会跳过它吗?