繁体   English   中英

如何在LINQ查询中根据日期条件选择列

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

我的查询是我想选择出生日期为系统日期的用户列表,我在控制器中使用了以下条件,但出现错误。 我想省略年份,并选择出生日期与系统日期和月份相同的用户。

错误:

LINQ to Entities无法识别方法'System.String ToString(System.String)',并且该方法无法转换为商店表达式。

控制器代码:

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在模型中定义为:

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

如何解决此错误并获取用户名?

这将使所有今天拥有DOB的用户:

如果DOB为DateTime类型:

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

如果DOB数据类型为Nullable DateTime( DateTime? ),则需要首先检查null并将DOB转换为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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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