【发布时间】:2020-07-23 18:49:38
【问题描述】:
当我尝试通过生日属性在 dataGridView 中显示年龄时出现以下错误
LINQ to Entities 无法识别方法 'Int32 CalculateAge(System.Datetime) 方法,并且该方法无法转换为存储表达式
这是我用来计算年龄的函数:
private int CalculateAge(string birthday)
{
int age;
if (string.IsNullOrWhiteSpace(birthday)) return 0;
DateTime empBirthday = Convert.ToDateTime(birthday);
DateTime today = DateTime.Today;
age = today.Year - empBirthday.Year;
if (empBirthday > today.AddYears(-age))
age--;
return age;
}
这是显示在 datagradView 上
var employee = db.Employee.Where(x => x.EmployeeId == id ).
Select(b => new
{
Id = b.EmployeeId,
Namn = b.FirstName + " " + b..LastName,
Age = CalculateAge(b.DOB.ToString()),
Department = b.Department.DepartmentName
} ).Tolist();
if employee != null)
{
dgvEmployee.DataSource = null;
dgvEmployee.DataSource = employee
}
但它不适用于 CalculateAge 函数。我该怎么做才能解决这个问题?请帮助,并在此先感谢您: 错误信息是 "LINQ to Entities 无法识别方法 'Int32 CalculateAge(System.Datetime) 方法,并且该方法无法转换为存储表达式"
【问题讨论】:
-
与问题无关,但假设
DOB是DateTime(可能是DateTime?),你为什么要把它转换成String(b.DOB.ToString())然后再转换它再次发给DateTime(Convert.ToDateTime(birthday))? -
@ Anderson Pimentel 感谢您的回复,但我什至尝试过使用 Datetime 但遇到了同样的问题
标签: c# entity-framework linq