【问题标题】:c#, LINQ to Entities does not recognize the method 'Int32 [duplicate]c#,LINQ to Entities 无法识别方法'Int32 [重复]
【发布时间】: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) 方法,并且该方法无法转换为存储表达式"

【问题讨论】:

  • 与问题无关,但假设DOBDateTime(可能是DateTime?),你为什么要把它转换成Stringb.DOB.ToString())然后再转换它再次发给DateTime (Convert.ToDateTime(birthday))?
  • @ Anderson Pimentel 感谢您的回复,但我什至尝试过使用 Datetime 但遇到了同样的问题

标签: c# entity-framework linq


【解决方案1】:

尝试查询您需要的数据,然后将集合转换为IEnumerable<T>,然后使用CalculateAge() 方法。

var employee = db.Employee.Where(x => x.EmployeeId == id ).
               Select(e => new { e.EmployeeId, e.FirstName, e.LastName, e.DOB, e.Department.DepartmentName }).
               AsEnumerable().
               Select(b => new
               {
                  Id = b.EmployeeId, 
                  Name = b.FirstName + " " + b.LastName,
                  Age = CalculateAge(b.DOB.ToString()),
                  Department = b.DepartmentName
                  } ).Tolist();
if employee != null)
{
   dgvEmployee.DataSource = employee;
}

【讨论】:

  • 感谢您的回复。我忘了显示部门名称,(我已经编辑了我的问题)我的员工类中有 DepartmentId 作为部门 yable 的外键。所以如果你编辑你的代码,那么它应该是怎样的呢?我把它放在 e.Department.DepartmentName 但在 select => b 它不起作用 b,Department.DepartmentName
  • 您好,我根据您的评论进行了编辑。也许这会奏效。
  • dgvEmployee.DataSource = null 是多余的,你不需要它。
  • @Anthony McGrath,非常感谢,它运行良好。再次感谢您
猜你喜欢
  • 2016-09-07
  • 1970-01-01
  • 2011-07-11
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 2014-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多