繁体   English   中英

什么是以下sql查询的linq等价物

[英]What is the linq equivalent of the below sql query

select Productid from categories where `categoryname` in `('abc','def','ghi')`; 

我试过这个:

var res = from catg in db.Categories where catg.CategoryId.ToString().Contains(SelectedProducts) select catg;

但这似乎不起作用......

假设SelectedProducts是一个产品ID数组(整数):

var cats = db.Categories.Where(o => SelectedProducts.Contains(o.CategoryId));
var pids = cats.Select(o => o.ProductId);

原因:SQL IN运算符在LINQ to SQL中相反实现。 这个问题突出了LINQ开发人员试图从SQL转换的一个常见错误,期望[attribute] [operator] [set]语法。

使用抽象集语言,我们可以突出显示语法差异

  • SQL使用“元素is included在Set中”语法
  • LINQ使用“Set contains Element”语法

因此必须使用Contains运算符还原任何IN子句。 无论如何它将转换为attribute IN (SET)

您需要在SelectedProducts上使用Contains

var res = from catg in db.Categories where 
SelectedProducts.Contains(catg.categoryname) select catg.Productid;

使用方法表示法

var res = db.Categories.Where(catg => SelectedProducts
            .Contains(catg.categoryname)).Select(catg.Productid);

SQL IN与IEnumerable.Contains()的等价性:

var res = from catg in db.Categories 
          where new[] {"abc","def","ghi"}.Contains(catg.categoryname) 
          select catg.Productid

或者lambda

db.Categories.Where(x => new[] {"abc","def","ghi"}.Contains(x.categoryname)).Select(c => c.ProductId);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM