2010-08-20 49 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; 
}