簡體   English   中英

如何在linq查詢中調用自定義方法

[英]How to call custom method in linq query

我寫一個自定義方法,如下所示:

 DateTime GetGregorianDate(string date)
    {
       return  new DateTime(int.Parse(date.Substring(0, 4)), int.Parse(date.Substring(5,    2)), int.Parse(date.Substring(8, 2)), new System.Globalization.PersianCalendar());
    }

我想在linq查詢中調用此方法,如下所示:

 dynamic GetPlayerListByTeamName(string teamCode, FutsalEntities myEntity)
    {
        var player = (from p in myEntity.Players
                     where p.TeamCode == teamCode && (GetGregorianDate(p.ContractDateTo) <= DateTime.Now) ? true : false
                     select new { p.MeliCode, p.BearthDate, p.ContractNumber, p.InsuranceNumber, p.ContractDate, p.Mobile });
        return player;

    }

這是代碼調用的地方:

  private void cmbTeams_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (FutsalEntities myEntity = new FutsalEntities())
        {
            if (cmbTeams.SelectedIndex != -1 && myEntity.Players.Count() != 0)
            {
               dgPlayerList.DataSource =  GetPlayerListByTeamName(cmbTeams.SelectedValue.ToString(), myEntity);

但是當我運行應用程序時出現此錯誤:

LINQ to Entities無法識別方法'System.DateTime GetGregorianDate(System.String)'方法,並且此方法無法轉換為商店表達式。

有沒有辦法在linq查詢中調用此方法?

Linq to Entities無法將您的方法轉換為SQL並在服務器端執行它。 調用自定義方法的唯一方法是將查詢移動到內存中 - 例如,通過調用AsEnumerable()ToList()

var players = from p in myEntity.Players.AsEnumerable()                      
              where GetGregorianDate(p.ContractDateTo) <= DateTime.Now
              select new { 
                  p.Name,
                  p.BearthDate, 
                  p.ContractNumber, 
                  p.InsuranceNumber, 
                  p.ContractDate, 
                  p.Mobile 
              };

請記住,這會將所有玩家數據通過網絡傳輸到本地計算機。

將DateTime.Now轉換為波斯日期,將其存儲在變量中,然后在查詢中使用該變量,以便服務器端查詢將進行波斯日期比較。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM