0

I need to fetch Previous Month Invoice from database for a particular user based on his/her relationship number. I have come up with below linq query.

// step 1: fetching Bill number based on relationship number and OrderByDescending clause
**

var query = context.Billings 

 .OrderByDescending(c => c.BillGenerationDate)
                               .Where(c => c.CAFNO == caf)
                               .Select(c => c.BillNo)
                               .FirstOrDefault();

** //step 2 : step 1 result have the bill number which was the last(or highest) filtered by //BillGeneration date

var bill = (from b in context.Billings
                            where b.BillNo == query
                            select b).FirstOrDefault();

step 2 will result the full bill information required.

OR

Other way :

var myresult = (from c in context.Billings
                            where c.CAFNO == caf
                            orderby c.BillGenerationDate descending
                            select c).FirstOrDefault();

I feel the above query can be re-written in better way. Looking for suggestion to re-write the above query in more efficient manner.

Thanks !!!

4

1 回答 1

0

由于可以BillGenerationDate为空而更新

您当前的查询将为您提供最后可用的帐单信息,而不是上个月的发票。要简洁地获得上个月,您可以执行以下操作。

var invoice = context.Billings
                     .FirstOrDefault( 
                         c => c.CAFNO == caf && 
                              (c.BillGenerationDate ?? new DateTime()).AddMonths(1).Month == DateTime.Now.Month &&
                              (c.BillGenerationDate ?? new DateTime()).AddMonths(1).Year == DateTime.Now.Year)

但是,如果您每月有超过一张发票,这并不能保证任何订单,您可以再次添加订购短语。

var invoice = context.Billings
                     .OrderByDescending(c => c.BillGenerationDate)
                     .FirstOrDefault( 
                         c => c.CAFNO == caf && 
                              (c.BillGenerationDate ?? new DateTime()).AddMonths(1).Month == DateTime.Now.Month &&
                              (c.BillGenerationDate ?? new DateTime()).AddMonths(1).Year == DateTime.Now.Year)

注意:这与您上面的第二个查询(除了额外的月份过滤器)并没有什么不同,因为FirstOrDefault(Func<T,Bool)重载就像组合一样,Where(Func<T,Bool>).FirstOrDefault()所以您选择哪个更具可读性。

于 2012-12-13T09:43:32.670 回答