2010-08-20 70 views
9

您对在项目中设计linq代码有什么建议? 特别是,我对大型复杂的linq查询的代码设计感兴趣?LINQ代码设计

例如,你知道,你需要写很多的巨大LINQ的东西,也许有些你的代码都会有重复部分,也许不是,你需要:

  1. 容易使代码支持 - 意味着,如果你需要改变一些东西。 - 你正在改变一件事,并不是很多

  2. 使代码易于阅读 - 意味着,如果你需要找到一些东西 - 你很容易做到这一点。

你可以使用你的例子,也许你的做法。也许一些模式,你看到的任何地方 - 任何东西。

说LINQ我的意思是任何LINQ,LINQ to SQL中的LINQ to Objects,LINQ到XML等

TNX

+1

不要忘记标记您最喜欢的答案。 NetSide的答案将是一个很好的候选人。 – Steven 2010-11-23 20:19:32

回答

7

,你可以写你的对象扩展;

主代码;

IQuerable itemList = _coreRepository.GetSomeItems() 
       .WithStates(OperationIdentity.SendToSomeWhere) 
       .BetweenDates(StartDate, EndDate); 

扩展;

public static IQueryable<SomeObject> BetweenDates(this IQueryable<SomeObject> query, DateTime startDate, DateTime endDate) 
     { 
      return from p in query 
        where p.CompletedDate >= startDate && p.CompletedDate < endDate 
        select p; 
     } 
3

我喜欢抛开使用扩展方法多次使用的大型Select语句。

public static IQueryable<SomeEntityPM> SelectEntityPM(this IQueryable<SomeEntity> entities) 
{ 
    return entities.Select(a => new SomeEntityPM { ... }); 
} 

用途:本

ObjectCtx.SomeEntities.SelectEntityPM(); 
2

一个有用的模式是建立一个可重用的谓词库。查看LINQ PredicateBuilder的更多信息。

2

一个VEW的事情我经常这样做:

1)布局:总是从下一行的查询。例如: 别这样

var allCustomersThatDontContainUnpayedOrders = from customer in db.Customers 
               where customer.Orders ... 
               select customer; 

但做到这一点:

var allCustomersThatDontContainUnpayedOrders = 
    from customer in db.Customers 
    where customer.Orders ... 
    select customer; 

2)使用多个where条款,你可以。我试图找到第二个片段比第一更易读:

var results = 
    from customer in db.Customers 
    where customer.Name.Contains(search) && customer.Address.City != null && 
     customer.Employee.IsSenior 
    select customer; 

var results = 
    from customer in db.Customers 
    where customer.Name.Contains(search) 
    where customer.Address.City != null 
    where customer.Employee.IsSenior 
    select customer; 

3)防止,如果你能加入。 LINQ to SQL通常允许您在不使用难以理解的join语句的情况下对所有父子关系进行“点”化。

4)通常你会看到许多查询看起来很相似。您可能总是希望根据用户的权限过滤某些记录。您可以通过以下方法提取此代码:

var customers = db.Customers; 

customers = FilterBasedOnUserRights(customers, currentUser); 

public static IQueryable<Customer> FilterBasedOnUserRights(
    IQueryable<Customers customers, User currentUser) 
{ 
    return 
     from customer in customers 
     where [big complicated where clause] 
     select customer; 
}