给定LINQ to Entities不支持“自定义方法”你怎么留下DRY? [英] Given LINQ to Entities does not support "Custom methods" how do you stay DRY?

查看:117
本文介绍了给定LINQ to Entities不支持“自定义方法”你怎么留下DRY?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这个问题:

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

基本上我有一些复杂的LINQ查询,所以想把它们分解成子查询实现为返回IQueryable的方法。我希望这些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 [Thread]
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与实体保持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.

更新刚刚看到更好的解释选项# 1 来自Damien Guard。

Update Just saw an even better explanation of option #1 from Damien Guard.

这篇关于给定LINQ to Entities不支持“自定义方法”你怎么留下DRY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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