鉴于 LINQ to Entities 不支持“自定义方法"你如何保持干燥? [英] Given LINQ to Entities does not support "Custom methods" how do you stay DRY?

查看:20
本文介绍了鉴于 LINQ to Entities 不支持“自定义方法"你如何保持干燥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了这个问题:

自定义方法 &扩展方法无法转换为存储表达式

基本上我有一些复杂的 LINQ 查询,所以想把它们分解成子查询,这些子查询被实现为返回 IQueryables 的方法.我希望这些 IQueryable 可以在 LINQ 语句中组合在一起(因为我很确定您可以在 LINQ to SQL 中做到这一点).

Basically I have some complicated LINQ queries, so wanted to break them down into subqueries which are implemented as methods that return IQueryables. My hope was then these IQueryables could be composed together in a LINQ statement (as I am pretty sure you can do in LINQ to SQL).

问题是如果你尝试这个你会得到(例如):

The problem is if you try this you get (for example):

LINQ to Entities 无法识别方法'System.Linq.IQueryable`1[线程]GetThreadsByMostReccentlyPosted(Int32)'方法,而这个方法不能翻译成商店表达.

LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[Thread] GetThreadsByMostReccentlyPosted(Int32)' method, and this method cannot be translated into a store expression.

对我来说,如果您使用 LINQ ORM,那么您需要能够编写 LINQ 查询,这似乎非常重要.否则,任何常见的查询逻辑都必须复制 &粘贴.

It seems pretty fundamental to me that if you use a LINQ ORM then you need to be able to compose LINQ queries. Otherwise any common query logic has to be copy & pasted.

鉴于此限制,我应该如何使用 LINQ to Entities 保持 DRY?

Given this limitation, how am I supposed to stay DRY with LINQ to Entities?

推荐答案

两种方式:

  1. 可以使用返回表达式的方法
  2. 分离可查询位和可枚举位

对于#1,请考虑:

public Expression<Func<Foo, bool>> WhereCreatorIsAdministrator()
{
    return f => f.Creator.UserName.Equals("Administrator", StringComparison.OrdinalIgnoreCase);
}

public void DoStuff()
{
    var exp = WhereCreatorIsAdministrator();
    using (var c = new MyEntities())
    {
        var q = c.Foos.Where(exp); // supported in L2E
        // do stuff
    }
 }

有关数字 2 的示例,请阅读这篇文章:如何组合 L2O 和 L2E 查询.考虑那里给出的例子:

For an example of number 2, read this article: How to compose L2O and L2E queries. Consider the example given there:

var partialFilter = from p in ctx.People
                    where p.Address.City == "Sammamish"
                    select p;

var possibleBuyers = from p in partiallyFilter.AsEnumerable()
                     where InMarketForAHouse(p);
                     select p;

这可能效率较低,也可能没问题.这取决于你在做什么.对于预测来说通常没问题,但对于限制来说通常不行.

This might be less efficient, or it might be fine. It depends on what you're doing. It's usually fine for projections, often not OK for restrictions.

更新刚看到Damien Guard 对选项 #1 的更好解释.

这篇关于鉴于 LINQ to Entities 不支持“自定义方法"你如何保持干燥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆