有没有更好的方式编写此Linq查询 [英] Is there a better way of writing this Linq Query

查看:53
本文介绍了有没有更好的方式编写此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#中的条件有了更多的控制,我该如何对where条件进行控制,而仅当有过滤器可用时才将where条件置于

When i trun on the profile it has a lot of case statements as i expect it to have. but i have lot more control on the condition what i put in in C# how can i exersise my control on the where condition and only put the where condition when filter is available for it

这将提高我进入数据库的sql的质量.

This will improve my quality of sql which goes to the db.

亲切的问候 维奈.

推荐答案

此类问题的一般解决方案是使用 PredicateBuilder 以动态构造适当的谓词.

A general solution for this sort of issue is to use PredicateBuilder to dynamically construct the appropriate predicate.

首先,建立谓词:

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};      

这篇关于有没有更好的方式编写此Linq查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆