Sameep Baxi
Sameep Baxi

Reputation: 111

How to select a column based on date condition in LINQ query

My query is I want to select list of users whose date of birth is system date, I have used the following condition in my controller, but it is giving an error. I want to omit year, and select users whose date of birth is same as system's date and month.

Error:

LINQ to Entities does not recognize the method 'System.String ToString(System.String)' method, and this method cannot be translated into a store expression.

Controller Code:

objUser.UserBirthdays = dbContext.EmployeeProfiles.Where(u => Convert.ToDateTime(u.DOB).ToString("dd-MMM").Equals(DateTime.Now.ToString("dd-MMM"))).Select(u => u.Name).ToList();

UserBirthdays is defined in the model as :

public IEnumerable<string> UserBirthdays { get; set; }

How to resolve this error, and get usernames?

Upvotes: 0

Views: 1827

Answers (1)

adiga
adiga

Reputation: 35253

This will get all the users with DOB today:

If DOB is of DateTime Type:

objUser.UserBirthdays = dbContext.EmployeeProfiles
                          .Where(u => u.DOB.Day == DateTime.Today.Day 
                                   && u.DOB.Month == DateTime.Today.Month)
                          .Select(u => u.Name).ToList();

If the DOB data type is Nullable DateTime (DateTime?), then you need to check for nulls first and convert the DOB to DateTime:

objUser.UserBirthdays = dbContext.EmployeeProfiles
                          .Where(u => u.DOB != null 
                                    && Convert.ToDateTime(u.DOB).Day == DateTime.Today.Day
                                    && Convert.ToDateTime(u.DOB).Month == DateTime.Today.Month)
                          .Select(u => u.Name).ToList();

Upvotes: 2

Related Questions