LINQ Lambda和SQL语句之间的区别

时间:2017-08-11 11:51:54

标签: c# sql linq lambda

我有以下lambda语句:

var resources = Db.Resource.Where(w => w.ResValue.Any(a => a.ApplicationFk == applicationPk) && w.CategoryFk == (categoryId ?? w.CategoryFk ) && w.IsEditable);
if (cultureIdsMissing!= null)
{
     resources = resources.Where(w => w.ResValue.Any(a => cultureIdsMissing.Any(aa => aa == a.CultureFk) && a.Value == string.Empty));
 }

这不会返回我想要的结果,它返回:

SELECT Resource.ResourcePk, Resource.CategoryFk, Resource.Name, Resource.IsEditable, ResValue.ApplicatieFk, ResValue.CultureFk, ResValue.Value
FROM Resource 
INNER JOIN ResValue ON Resource.ResourcePk = ResValue.ResourceFk
WHERE (ResValue.ApplicatieFk = 6) 
AND (Resource.IsEditable = 1) 
AND (ResValue.Value = '') 
AND (ResValue.CultureFk = 1 OR ResValue.CultureFk = 2)

不是cultureIdsMissing是包含数字1和2的List。 我对lambda查询缺少什么或做错了什么?

3 个答案:

答案 0 :(得分:0)

我认为您必须从linq lemda表达式中删除&& w.CategoryFk == (categoryId ?? w.CategoryFk )。如果categoryId = 1,则只会使用值为1的记录。所以在删除之后再尝试。您的linq代码应为此。

var resources = Db.Resource.Where(w => w.ResValue.Any(a => a.ApplicationFk == applicationPk)&& w.IsEditable);
if (cultureIdsMissing!= null)
{
    resources = resources.Where(w => w.ResValue.Any(a => cultureIdsMissing.Any(aa => aa == a.CultureFk) && a.Value == string.Empty));
}

答案 1 :(得分:0)

你应该从你的sql语句中获取它:

Db.Resource
.Join(Db.ResValue
, rs => rs.ResourcePk
, resV => resv.resourceFk
, (rs, resv) => new { res = rs, resV = resV })
.Where(w => w.resv.ApplicatieFk == 6
&& w.res ==1
&& resv.Value == string.empty()
&& (resv.CultureFk == 1 || resv.CultureFk == 2))

它没有经过测试,所以也许它不会在第一次尝试时工作。

答案 2 :(得分:0)

我会将SQL翻译成查询理解语法。通常,在查询理解顺序中转换短语,使用表别名作为范围变量(或创建范围变量),并放置一元/整体聚合函数(例如TOPDISTINCTSUM )作为函数调用整个查询之外。对于您的SQL,

var ans = from r in Resource
          where r.IsEditable == 1
          join rv in ResValue on r.ResourcePk equals rv.ResourceFk
          where rv.ApplicatieFk == 6 && rv.Value == "" && (rv.CultureFk == 1 || rv.CultureFk == 2)
          select new { r.ResourcePk, r.CategoryFk, r.Name, r.IsEditable, rv.ApplicatieFk, rv.CultureFk, rv.Value };