請參閱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