2011-02-15 64 views
2

有沒有寫這個LINQ查詢

from O in db.Orders 
join C in db.Customers on C.Id equals O.CustID 
Where O.ord_date == (filter.OrderDate != null ? filter.OrderDate : o.ord_date) && 
    c.Id == (filter.CustId != null ? filter.CustId : c.Id) && 
    o.ProductId == (filter.ProductId != null ? filter.ProductId : o.ProductID) 
select new {o,c} 

//select new {c.Name, C.JoinDate, O.Value, O.NoofLineItems } 

一個更好的方式。當我對真理的輪廓它有很多case語句,因爲我希望它有。但我有更多的控制條件,我放在C#我如何exersise我的控制在哪裏條件,只放在哪裏條件,當過濾器是可用的它

這將改善我的質量sql到數據庫。

親切的問候 Vinay。

回答

2

這種問題的一般解決方案是使用PredicateBuilder來動態構造適當的謂詞。

一是建設謂詞:

Expression<Func<Order, bool>> predicate = PredicateBuilder.True<Order>(); 

if (filter.OrderDate != null) 
    predicate = predicate.And(o => o.ord_date == filter.OrderDate); 

if (filter.CustId != null) 
    predicate = predicate.And(o => o.CustId == filter.CustId); 

... 

然後你的查詢變爲:

var filtered = db.Orders.Where(predicate); 

var query = from O in filtered 
      join C in db.Customers on C.Id equals O.CustID 
      select new {o,c};  
+2

+1 - PredicateBuilder是真正優秀的,我強烈推薦給任何使用Linq的人。 – 2011-02-15 16:06:01

0

也許它改成這樣:

from O in db.Orders 
join C in db.Customers on C.Id equals O.CustID 
Where O.ord_date == (filter.OrderDate ?? o.ord_date) && 
    c.Id == (filter.CustId ?? c.Id) && 
    o.ProductId == (filter.ProductId ?? o.ProductID) 
select new {o,c} 

使用?? operator讓事情有點整潔。它基本上就像一個.NET的聯合運算符。除此之外,我不確定還有什麼可以改變的。

+0

那是不可能重寫它,就像 從db.OrdersØ 在C.Id db.Customers加入C等於O.CustID 凡 \t如果(filter.OrderDate!= NULL) \t \t O. ord_date == filter.OrderDate && \t如果(filter.CustId!= NULL) \t \t c.Id == filter.CustId && \t如果(filter.ProductId!= NULL) \t \t o.ProductId ==過濾器.ProductId 選擇新{o,c} – bhushanvinay 2011-02-15 17:56:54

2

由於不依賴於查詢條件,你可以有出條件語句的查詢,並逐步構建它:

var query = from o in db.Orders 
      join c in db.Customers on c.Id equals o.CustID 
      select new {o,c}; 
if(filter.OrderDate != null) 
{ 
    query = query.Where(x => x.o.ord_date == filter.OrderDate); 
} 
if(filter.CustId != null) 
{ 
    query = query.Where(x => x.c.Id == filter.CustId); 
} 
if(filter.ProductId != null) 
{ 
    query = query.Where(x => x.o.ProductID == filter.ProductId); 
}