2013-07-05 36 views
0

是否可以在LINQ表达式中使用先前定义的expressionquery syntax?我创造了一个人为的例子来说明我的问题。在LINQ查询语句中预先定义的表达式

var tabletTypes = new List<int> { 2, 3 }; 
//I want to use this expression many times 
Expression<Func<Computer, bool>> isTablet = comp => tabletTypes.Contains(comp.Type); 

var computers = db.Computers; 
var producers = db.Producers; 

//I know how to use the expression in fluent syntax 
IQueryable<Producer> tabletProducers = computers 
           .Where(isTablet) 
           .Join(producers, 
            comp => comp.ProducerId, 
            producer => producer.Id, 
            (comp, producer) => producer); 

//How can I use the expression in query syntax 
IQueryable<Producer> tabletProducers2 = from c in computers 
             join p in producers 
              on c.ProducerId equals p.Id 
             where /*How can I use isTablet here?*/ 
             select p; 


public class Producer 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
} 

public class Computer 
{ 
    public int Id { get;set; } 
    public int Type { get; set; } 
    public int ProducerId { get; set; } 
} 

我使用C#5和EF 5

+1

如果使用表达式树,则可以这样做。看看[LinqKit](http://www.albahari.com/nutshell/linqkit.aspx),特别是'Expand()'功能。 –

+0

@SimonBelanger我从未使用过LinqKit。它看起来很有趣。 –

+0

是的 - 该页面也解释了为什么我的答案不起作用 – Rob

回答

0

你可以只使用where isTablet.Compile()(c)。您可能想缓存编译后的版本。

+0

使用这会产生实体框架错误“LINQ to Entities不支持LINQ表达式节点类型'Invoke'。” –

+0

为了更深入地解释我的评论......这个答案可以使用IEnumerables而不是IQueryables。 –