[英]SQL to LINQ translation
SELECT * FROM Recipe WHERE ID IN
(SELECT RID FROM Recipe_Ingredient WHERE IID IN
(SELECT MIN(ID) FROM Ingredients WHERE Name IN('broccoli','egg')))
I am trying to translate this sql query into linq. 我正在尝试将此sql查询转换为linq。 So far I got no luck. 到目前为止,我还没有运气。
I receive a string array of ingredients. 我收到了一堆配料。 So far I got to this: 到目前为止,我明白了这一点:
List<string> searchList = new List<string>(search);
var ing = context.Ingredients.Where(x => x.Name.Contains(searchList.ToString())).ToList();
var recing = context.Recipe_Ingredients.Where(x => ing.Contains(x.IID)).Select(x => x.IID).ToList();
var rec = context.Recipes.Where(x => recing.Contains(x.ID)).ToList();
But by using the debugger it fails on the ing
because the searchList
is not contained in x.Name
( searchList[0] = 'egg'
when I use it for testing) 但是,通过使用它的失败调试器ing
因为searchList
不包含x.Name
( searchList[0] = 'egg'
当我使用它用于测试)
You have small mistake in ing line. 您在ing行中有个小错误。 And first 2 ToList methods are redundant. 并且前两个ToList方法是多余的。
List<string> searchList = new List<string>(search);
var ing = context.Ingredients.Where(x => searchList.Contains(x.Name));
var recing = context.Recipe_Ingredients.Where(x => ing.Contains(x.IID)).Select(x => x.IID);
var rec = context.Recipes.Where(x => recing.Contains(x.ID)).ToList();
You are not translating the MIN(...)
in the SQL. 您没有在SQL中转换MIN(...)
。
var searchList = new List<string>(search); // broccoli, egg
var recipies = context.Recipes
.Where(r =>
context.Recipe_Ingredients
.Where(ri =>
context.Ingredients
.Where(i => searchList.Contains(i.Name))
.Select(i => i.ID)
.Min() == ri.IID
)
.Select(ri => ri.RID)
.Contains(r.ID)
)
.ToList();
ToList()
too early, it will generate multiple queries. 不要过早地放入ToList()
,它会生成多个查询。 So to stay near your code, you could do 因此,要保持靠近代码的位置,您可以
List<string> searchList = new List<string>(search);
var ingId = context.Ingredients.Where(x => searchList.Contains(x.Name)).Min(m => m.Id);
var recing = context.Recipe_Ingredients.Where(x => x.IID == ingId).Select(x => x.RID);
var rec = context.Recipes.Where(x => recing.Contains(x.ID)).ToList();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.