简体   繁体   中英

How to search Database using a Datetime field in LINQ?

I have a search button and textfield where the user can insert Payment Date and pressing the button will show the Search result in a Gridview row. I have a similar code to search database but for string value. Here is my code:

  public List<PaymentsHeader> GetPaymentsMadeForSearch(string keyword)
    {

        CosisEntities db = new CosisEntities();
        IQueryable<PaymentsHeader> query = db.PaymentsHeaders.OrderByDescending(m => m.PaymentDate);
        if (!string.IsNullOrEmpty(keyword))
        {
            keyword = keyword.ToLower();
            query = query.Where(m =>
                    (!string.IsNullOrEmpty(m.VendorID) && m.VendorID.ToLower().Contains(keyword))
                || (!string.IsNullOrEmpty(m.CheckNumber) && m.CheckNumber.ToLower().Contains(keyword))
                 || (!string.IsNullOrEmpty(m.Notes) && m.Notes.ToLower().Contains(keyword))
                || m.PaymentsDetails.Select(j => j.Description).Contains(keyword)
                );
        }

        return query.ToList();

    }

so, here in this code the I am searching through the table using a string field but my requirement is to search the table using the Payment Date. So, for that I need to convert the field

 String Keyword

into datetime. But unfortunately I don't know how to do this. Can anyone help me please to modify the above code to meet the requirement. Thank you.

DateTime date;
bool isDate = DateTime.TryParse(keyword, out date);

DateTime? date2 = isDate ? (DateTime?)date : null;

and then

|| m.PaymentDate == date2

In sql, null is always different from anything (even from null , so null != null ), so if the keyword isn't a date, in date2 you'll have null , and the check will always return false (but note that this will perhaps change in the future of EF: http://data.uservoice.com/forums/72025-ado-net-entity-framework-ef-feature-suggestions/suggestions/1015361-incorrect-handling-of-null-variables-in-where-cl?ref=title%23suggestion-1015361 )

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