过滤包括实体框架中的项目

时间:2017-07-20 18:11:51

标签: linq lambda include

我已经阅读了这个post,我在EntityFramework核心中实现了一个linq查询。 这是c#语法:

    DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
    var actionMenuGroup = Context.ActionMenuGroups
                  .Include(am => am.ActionMenus)
                  .Where(am => am.ActionMenus.Any(amm => amm.DeliveryDate.GetValueOrDefault(DateTime.MinValue).CompareTo(today) <= 0 && amm.AuthorizedCustomers.Any(ac => ac.CustomerId.Equals(CustomerId) && ac.DeliveryDate.GetValueOrDefault(DateTime.MinValue).CompareTo(today)<=0)))
                  .Select(g => new ActionMenuGroup()
                  {
                      Id = g.Id,
                      Name = g.Name,
                      SortOrder = g.SortOrder,
                      ActionMenus = g.ActionMenus.Where(amm => amm.DeliveryDate.GetValueOrDefault(DateTime.MinValue).CompareTo(today) <= 0 && amm.AuthorizedCustomers.Any(ac => ac.CustomerId.Equals(CustomerId) && ac.DeliveryDate.GetValueOrDefault(DateTime.MinValue).CompareTo(today) <= 0)).ToList()
                  });

一切正常! 但是,在插入lambda过滤器表达式后,select会出错;这是lambda的新版本:

public Func<Model.ActionMenu, DateTime, int?, bool> filterActionMenu = (amm, oggi, CustomerId) => amm.DeliveryDate.GetValueOrDefault(DateTime.MinValue).CompareTo(oggi) <= 0 && amm.AuthorizedCustomers.Any(ac => ac.CustomerId.Equals(CustomerId) && ac.DeliveryDate.GetValueOrDefault(DateTime.MinValue).CompareTo(oggi) <= 0);

    public IQueryable<ActionMenuGroup> GetActionMenuAndMenuGroupByCustomer(int? CustomerId)
    {
        DateTime today = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
        var actionMenuGroup = Context.ActionMenuGroups
                  .Include(am => am.ActionMenus)
                  .Where(am => am.ActionMenus.Any(amm => filterActionMenu(amm,today, CustomerId)))
                  .Select(g => new ActionMenuGroup()
                  {
                      Id = g.Id,
                      Name = g.Name,
                      SortOrder = g.SortOrder,
                      ActionMenus = g.ActionMenus.Where(amm => filterActionMenu(amm, today, CustomerId)).ToList()
                  });
        return actionMenuGroup;
    }

将lambda用于linq语法是否已经很容易? 感谢

1 个答案:

答案 0 :(得分:0)

尝试:

public Expression<Func<Model.ActionMenu, DateTime, int?, bool>>  filterActionMenu = (amm, oggi, CustomerId) => ....