【问题标题】:How do I just LINQ Join() to link two IQueryables?我如何只使用 LINQ Join() 来链接两个 IQueryables?
【发布时间】:2010-10-08 10:42:01
【问题描述】:

我有两个 IQueryable:

成分:

IngId
Description

可用成分:

IngId

我已经有一个 IQueryable 用于成分:

var ingQuery = from i in context.Ingredients
               select i;

如何向他添加一个联接,以便它按AvailableIngredient 过滤(即内部联接)?如果我必须一直加入,我知道该怎么做,即从...加入上下文。可用...等),但加入是有条件的,所以我需要使用其他语法:

if (filterByAvailable)
{
   IQueryable<Available> availableQuery = GetAvailableIngredientQuery(context);
   ingQuery = ingQuery.Join(...); // Can I use this to join to the query?
}

这可能不是正确的方法,所以这是我想做的:

  • GetAvailableIngredientQuery 返回 可用成分查询,即 6000 个中的 3000 个(但它没有 枚举结果,因为它是 从 EF 作为 IQueryable 返回)
  • 将 availableQuery 加入 ingQuery,因此两个查询之间存在 Inner Join

编辑:

这是我目前正在使用的代码(非常快),但这意味着重复的代码:

IQueryable<Ingredient> query;
if (filterByAvailable)
{
    IQueryable<Available> availableQuery = GetAvailableIngredientQuery(context);
    query = from item in context.Ingredients
               // Quite a few `where` clauses and stuff
            join t in availableQuery on item.IngId equals t.IngId
            select item;
}
else
{ 
    query = from item in context.Ingredients
               // The SAME `where` clauses and stuff as above
            select item;
}

【问题讨论】:

    标签: linq join c#-4.0 entity-framework-4 ef-code-first


    【解决方案1】:

    使用第一个查询作为后续查询的来源。

    IQueryable<Ingredient> query = from item in context.Ingredients
                                 // Quite a few `where` clauses and stuff
                                   select item;
    
    if (filterByAvailable)
    {
        IQueryable<Available> availableQuery = GetAvailableIngredientQuery(context);
        query = from item in query
                join t in availableQuery on item.IngId equals t.IngId
                select item;
    }
    

    【讨论】:

    • 这就是我已经拥有的。阅读我的编辑(在您的回答之前),它会导致大量重复。此外,这是无效的语法。您不能使用==,它必须是equals。还是谢谢。
    • 谢谢,看起来肯定会起作用(我不知道我为什么要尝试这个)!不幸的是,我目前处于完全无法建造的状态,所以我会尝试一下。
    • 正确。非常感谢!
    猜你喜欢
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 2020-04-19
    相关资源
    最近更新 更多