SQL到LINQ的翻译

时间:2014-05-12 11:53:12

标签: c# sql linq

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.NamesearchList[0] = 'egg'当我用它进行测试时不包含)

db schema

3 个答案:

答案 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)

  1. 您反转包含(您未执行条款)
  2. Min(Id)不能是一个列表(在你的sql查询中),它将是一个唯一的id。
  3. 过早放置ToList(),会产生多个查询。
  4. 所以要靠近你的代码,你可以做到

    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();