Is it possible to call named method within a call to Where?

让人想犯罪 __ 提交于 2020-01-14 09:11:30

问题


I am trying to understand some performance implication of Linq from this free ebook by RedGate ftp://support.red-gate.com/ebooks/under-the-hood-of-net-memory-management-part1.pdf

On page 157-158 in this book, they created following example.

Order[] pastDueAccounts = null;  
DateTimedueDate = DateTime.Today.AddDays(-7);  
using(varcontext = new Context())    
{  
    pastDueAccounts = context.Accounts.Where(account => account.DueDate < dueDate).ToArray();  
} 

They then re-factored part of lamda expression into following function.

public bool PastDueAccount(Account account)  
{  
    return account.DueDate < DateTime.Today.AddDays(-7);  
} 

Finally they used this function as follows.

Order[] pastDueAccounts = null;  
using(varcontext = new Context())  
{  
    pastDueAccounts = context.Accounts.Where(account => PastDueAccount(account)).ToArray();  
} 

Based on what I researched so far, its not possible to run this linq query as LINQ will not be able recognize the method and cannot be translate into a store expression. I wonder if this example is wrong and simply not possible to run or if I am just having hard time getting my heard around on how to simulate this problem?


回答1:


You are correct, this would not be able to be called by LINQ-to-Entities the way it's displayed.

The only way it could be used in LINQ-to-Entities is to:

  • Create the equivalent of the function on the server side.
  • Map the function in the model appropriately so that it translates the call correctly.



回答2:


As casperOne said, you can't do that with a function. This answer is a way to do what you need to do (reuse a where filter).

You can create an Expression somewhere you can access, then reuse it.

System.Linq.Expressions.Expression<Func<Account, bool>> pastDueAccountFunc = account => account.DueDate < System.Data.Objects.EntityFunctions.AddDays(DateTime.Now, -7);

Then to use it later:

var pastDueAccounts = context.Accounts.Where(pastDueAccountFunc);

This is the full code I'm using with this:

System.Linq.Expressions.Expression<Func<SomeNeatEntity, bool>> func = x => x.DateCreated < System.Data.Objects.EntityFunctions.AddDays(DateTime.Now, -7);

var entities = new MyEntities();

var t = entities.SomeNeatEntities.Where(func);
Console.WriteLine(t.Count());

var h = entities.SomeNeatEntities.Where(x => x.SomeField != null).Where(func);
Console.WriteLine(h.Count());

MyEntities is the ObjectContext in the project.
entities.SomeNeatEntities is ObjectSet<SomeNeatEntity>.



来源:https://stackoverflow.com/questions/12903138/is-it-possible-to-call-named-method-within-a-call-to-where

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!