请参阅calculateAge将LINQ查询中的出生日期转换为当前年数(它适用于其他键,例如:EyeColor,但适用于年龄转换失败),我想比较存储在数组中的值。我尝试将值存储在链接上方的DateTime temp变量中,正好在“case”AgeTo“:”下方,但我不能将值x.profile.BirthDate存储为仅在LINQ Query中允许的值。看来,在构建LINQ查询,不给错误,但是,它的失败精读从LINQ查询日期时间字段中计算年龄(使用C#进行比较)(Age From)
错误:
LINQ to Entities does not recognize the method 'Int32 calculateAge(System.DateTime)' method, and this method cannot be translated into a store expression.
任何帮助,如何处理?
代码和calculateAge方法:
if (searchList.Count > 0)
{
foreach (KeyValuePair<String, String> kvp in searchList)
{
switch (kvp.Key)
{
case "AgeFrom":
photosquery = photosquery.Where(x => calculateAge(Convert.ToDateTime(x.profile.BirthDate)) >= Convert.ToInt32(kvp.Value));
break;
case "AgeTo":
photosquery = photosquery.Where(x => calculateAge(Convert.ToDateTime(x.profile.BirthDate)) <= Convert.ToInt32(kvp.Value));
break;
case "EyeColor":
photosquery = photosquery.Where(x => x.physical.EyesColor.Contains(kvp.Value));
break;
}
}
}
//My code for calculateAge:
public static int calculateAge(DateTime birthDay)
{
int years = DateTime.Now.Year - birthDay.Year;
if ((birthDay.Month > DateTime.Now.Month) || (birthDay.Month == DateTime.Now.Month && birthDay.Day > DateTime.Now.Day))
years--;
return years;
}
你知道如果你在午夜附近执行你的代码,如果可能会失败吗?最好在当前时间只询问一次,以确保搜索列表中的所有项目都使用相同的时间进行比较。也更容易编写一个体面的规范:“该函数计算函数被调用时集合中所有项目的年龄”。无论程序执行的速度如何,结果都是可预测的。另外考虑使用DateTime.Today,而不是DateTime.Now –
好的一点,我会改变代码,回到我的成功。 – dotNETEngineer