简体   繁体   English

如何在linq查询中调用自定义方法

[英]How to call custom method in linq query

i write a custom method like below : 我写一个自定义方法,如下所示:

 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());
    }

and i want call this method in linq query like below : 我想在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;

    }

This is where the code is called : 这是代码调用的地方:

  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);

but when i run application get this error : 但是当我运行应用程序时出现此错误:

LINQ to Entities does not recognize the method 'System.DateTime GetGregorianDate(System.String)' method, and this method cannot be translated into a store expression. LINQ to Entities无法识别方法'System.DateTime GetGregorianDate(System.String)'方法,并且此方法无法转换为商店表达式。

Is there any way to call this method in linq query? 有没有办法在linq查询中调用此方法?

Linq to Entities can't translate your method into SQL and execute it on server side. Linq to Entities无法将您的方法转换为SQL并在服务器端执行它。 The only way to call your custom method is to move query into memory - eg by calling AsEnumerable() or ToList() 调用自定义方法的唯一方法是将查询移动到内存中 - 例如,通过调用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 
              };

Keep in mind, that this will transfer all players data over the network to local computer. 请记住,这会将所有玩家数据通过网络传输到本地计算机。

将DateTime.Now转换为波斯日期,将其存储在变量中,然后在查询中使用该变量,以便服务器端查询将进行波斯日期比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM