Vicky
Vicky

Reputation: 61

Perform search by Date using entity framework

I try to make search query in Entity framework. I have table Project with 'Id', 'ProjectName', 'Description' and "modificationdate" etc. I want to perform search on 'ProjecName', 'Description' and "modificationdate". I successfully perform search on 'ProjectName' & 'Description' but i don't know how perform search by date

var found = from n in context.Project
                            where n.projectName.Contains(SearchKey) ||
                            n.description.Contains(SearchKey) 
                        select n;

Upvotes: 2

Views: 1755

Answers (2)

ta.speot.is
ta.speot.is

Reputation: 27214

To take what you're saying from the comments:

Actually i try to perform search on given date

If you want to search for modifications on a given date, just search for values greater than or equal to the start of the date and then everything less than the day after.

var searchDate = new DateTime(2013, 2, 5); // or searchDateWithTime.Date
var searchDatePlusOne = searchDate.AddDays(1);

return from n in context.Project
       where n.ModificationDate >= searchDate
             && n.ModificationDate < searchDatePlusOne
       select n;

If n.ModificationDate contains a date and nothing more, then n.ModificationDate == searchDate is a sufficient predicate.

Upvotes: 2

Henk Mollema
Henk Mollema

Reputation: 46551

You can use the greather-than >, less-than < and equals == operators for example (see this for a complete list) to search by date. Example to get projects modified a week ago or less:

DateTime.Now.AddDays(-7) > n.modificationdate

If you don't want to include the time, you can use the Date property to exclude it:

DateTime.Now.AddDays(-7).Date > n.modificationdate.Date

Edit: search by given date:

date == n.modificationdate

Where date is the given date. If the date is specified in the SearchKey variable (which I assume is a string), you have to parse it to a date first.

Upvotes: 2

Related Questions