SELECT * FROM Recipe WHERE ID IN
(SELECT RID FROM Recipe_Ingredient WHERE IID IN
(SELECT MIN(ID) FROM Ingredients WHERE Name IN('broccoli','egg')))
我正在尝试将此sql查询转换为linq。到目前为止,我没有运气。
我收到了一系列成分。到目前为止,我得到了这个:
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();
但是通过使用调试器,它在ing
上失败了,因为searchList
x.Name
(searchList[0] = 'egg'
当我用它进行测试时不包含)
答案 0 :(得分:0)
你在线上犯了小错误。前2个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();
答案 1 :(得分:0)
您没有翻译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();
答案 2 :(得分:0)
ToList()
,会产生多个查询。所以要靠近你的代码,你可以做到
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();