【问题标题】:How can Entity Framework queries be reused (using methods)?如何重用实体框架查询(使用方法)?
【发布时间】:2010-07-10 00:07:55
【问题描述】:

我正在尝试重用查询的一部分,因为它足够复杂,我想尽量避免代码重复。

似乎在查询中调用任何方法时,您最终会得到:

LINQ to Entities 无法识别 方法 {X} 方法,以及 这个方法不能翻译成 商店表达式

理想情况下我想做的是使用:

var q = from item in context.Items
        where item.SomeCondition == true
        select new {Item = item, Connections = GetConnections(item)};

GetConnections 是对item 执行查询的方法。我正在尝试重用 GetConnections 中的(相当复杂的)查询,但我不确定如何让它工作。

GetConnections 的当前签名类似于:

IQuerable<Connection> GetConnections(MyItem item)

【问题讨论】:

    标签: c# linq entity-framework linq-to-entities entity-framework-4


    【解决方案1】:
    Expression<Func<Customer, CustomerWithRecentOrders>>
      GetCustomerWithRecentOrdersSelector()
    {
      return c => new CustomerWithRecentOrders()
      {
        Customer = c,
        RecentOrders = c.Orders.Where(o => o.IsRecent)
      };
    }
    

    然后……

    var selector = GetCustomerWithRecentOrderSelector();
    var q = myContext.Customers
      .Where(c => c.SomeCondition)
      .Select(selector);
    

    【讨论】:

    • 知道当您没有IQuerable&lt;Customer&gt; 而只有Customer 时如何做同样的事情吗?这甚至可能吗?
    • CustomerWithRecentOrders x = myContext.Customers .Where(c => c == myCustomer) .Select(selector).Single()
    【解决方案2】:

    您的查询对我来说几乎是完美的。您当然可以在查询中致电GetConnections(item);调用方法是合法的。但是,您还有另一个问题:必须使用成员名称创建匿名类型成员(没有这些名称,您将无法访问它们)。

    以下查询对我来说编译得很好:

    var q = from item in context.Items
            where item.SomeCondition == true
            select new {item = item, connections = GetConnections(item)};
    

    注意item =connections = 添加到select

    但是请注意,您的 GetConnections() 方法可能需要为 static(我的方法是;我不确定您是否意外遗漏了它)。

    【讨论】:

    • 不是编译失败,而是执行。我没有复制/粘贴代码,而是用头部输入,这就是我忘记匿名类型成员的原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 2017-03-06
    • 2017-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多