简体   繁体   中英

Only include in where condition if date is not low date(01/01/0001)

I have a query that has a where condition to check and find addresses that were added after a certain date. The date field is not required so I want Date field in where condition to be only considered if it is not 1/1/0001. dtmDate is the parameter that is being passed

Query

from b in _context.customer
           join d in _context.Address on b.id equals d.Id 
           join e in _context.units on d.Id equals e.Id
           where (req.dtmDate.Year != 1 && d.DateAdded >= req.dtmDate)

select new modelAddress
              {
               address= d.address
              }

But this is not working. It is not returning any rows

I'd leverage the fact that LINQ queries are not executed when you write them, so you can add clauses conditionally after you've created a base query:

var query = from b in _context.customer
       join d in _context.Address on b.id equals d.Id 
       join e in _context.units on d.Id equals e.Id;

if(req.dtmDate.Year != 1)
  query = query.Where(d.DateAdded >= req.dtmDate);

var result = query.Select(
  new modelAddress
  {
    address= d.address
  }
);

I prefer this because I've previously run into issues, particularly with EF LINQ queries when the Where clause contains something that evaluates to true locally with in the code, rather than as something the DB will evaluate. It seems to work out better when "wildcarding" DB queries, to use a pattern of "if x is true then add-another-where-clause" rather than saying "where(local-value-of-x-equals-local-constant OR some-db-data-value-equals-y)"

If I understand you correctly, you have a DateTime object called req.dtmDate that may be set to a default value, and you want to return all items where the item's DateAdded field is greater than req.dtmDate , unless req.dtmDate is 1/1/0001 , in which case all records should be returned.

If that's the case, I think you could just modify your existing code to:

where (req.dtmDate.Year == 1 || d.DateAdded >= req.dtmDate)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM