如何从linq查询中调用本地方法

时间:2017-04-03 15:29:04

标签: c# entity-framework linq asp.net-web-api azure-sql-database

在我的web api中,我需要从linq查询本身执行一个方法。我的linq查询代码片段属于下面显示的方法,它调用本地方法来获取所需的数据。

var onlineData = (from od in db.RTLS_ONLINEPERSONSTATUS
                  let zoneIds = db.RTLS_PERSONSTATUS_HISTORY.Where(p => p.person_id == od.PERSONID).OrderByDescending(z => z.stime > startOfThisDay && z.stime < DateTime.Now).Select(z => z.zone_id).ToList()

                  let zoneIdsArray = this.getZoneList((zoneIds.ToArray()))
                  let fzones = zoneIdsArray.Select(z => z).Take(5)
                  select new OnlineDataInfoDTO
                  {
                      P_ID = od.PERSONID,
                      T_ID = (int)od.TAGID,
                      LOCS = fzones.ToList()
                  }

public int[] getZoneList(decimal[] zoneIdsArray)
    {
        int[] zoneIds = Array.ConvertAll(zoneIdsArray, x => (int)x);
        List<int> list = zoneIds.ToList();
        for (int c = 1; c < zoneIdsArray.Count(); c++)
        {
            if (zoneIdsArray[c] == zoneIdsArray[c - 1])
            {
                list.Remove((int)zoneIdsArray[c]);
            }
        }
        return list.ToArray();
    }

我在let zoneIdsArray = this.getZoneList((zoneIds.ToArray()))中遇到异常,有没有办法解决这个问题。我有逻辑从这个链接(Linq query to get person visited zones of current day)解决我的问题,给定的逻辑绝对适合我的要求,但我在执行时遇到问题。

1 个答案:

答案 0 :(得分:1)

实现这一目标的一种方法是在客户端而不是底层LINQ提供程序上执行投影。这可以通过将您的查询分为两个步骤来完成:

var peopleStatus =
    from od in db.RTLS_ONLINEPERSONSTATUS
    let zoneIds = db.RTLS_PERSONSTATUS_HISTORY
        .Where(p => p.person_id == od.PERSONID)
        .OrderByDescending(z => z.stime > startOfThisDay && z.stime < DateTime.Now)
        .Select(z => z.zone_id)
        .ToList()
    select new
    {
        Person = od,
        ZoneIds = zoneIds,
    };

var onlineData =
    from od in peopleStatus.ToList()
    let zoneIdsArray = this.getZoneList((od.ZoneIds.ToArray()))
    let fzones = zoneIdsArray.Select(z => z).Take(5)
    select new OnlineDataInfoDTO
    {
        P_ID = od.Person.PERSONID,
        T_ID = (int)od.Person.TAGID,
        LOCS = fzones.ToList()
    };