簡體   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