LINQ Lambda:获取子集合的最后一项(where ==)

时间:2012-08-13 16:09:33

标签: c# linq entity-framework linq-to-entities

我有以下内容(我在CodeFirst中使用过):

public class MyForm
    {
        public int MyFormId { get; set; }
        //Many Form Properties
        public virtual ICollection<AuditItem> AuditItems { get; set; }
    }

public class AuditItem
    {
        public int AuditItemId { get; set; }
        public int MyFormId { get; set; }
        public IAppUser User { get; set; }
        public string ActionByUserStr { get; set; }
        public string ActionByUserDisplayName { get; set; }
        public DateTime DateOfAction { get; set; }
        public string TypeOfAction { get; set; }
        public int Step { get; set; }

        public virtual MyForm MyForm { get; set; }
    }

AuditItem跟踪在MyForm上执行的许多操作

我正在展示一个索引页面,其中显示了AuditItem的最后一步= 1的表格。

我通过DateOfAction执行命令(因为Step可以回退到0,所以我不希望它等于1,除非它也是该MyForm的最后一个AuditItem记录),然后选择最后一条记录的步骤,然后查询在那。我想尽早查询,以便我不会撤回不需要的MyForms记录。

这是我的查询:

var myFormsAtStep1 =
                context.MyForms.Include("AuditItems").Where(
                    mf => mf.AuditItems.OrderBy(ai => ai.DateOfAction).Last().Step == 1);

它给出了这个错误:

LINQ to Entities does not recognize the method 'MyForms.Models.AuditItem Last[AuditItem](System.Collections.Generic.IEnumerable`1[MyForms.Models.AuditItem])' method, and this method cannot be translated into a store expression.

2 个答案:

答案 0 :(得分:5)

查看Supported and Unsupported LINQ Methods列表。

Last()不受支持,First()不受支持,因此您可以继续修改订单并使用First()代替Last()

mf => mf.AuditItems.OrderByDescending(ai => ai.DateOfAction).First().Step == 1);

答案 1 :(得分:2)

您只需按降序排序并获得第一项。

var myFormsAtStep1 =
    context.MyForms.Include("AuditItems").Where(
        mf => mf.AuditItems.OrderByDescending(
            ai => ai.DateOfAction).First().Step == 1);

我还会使用更具可读性的查询语法,以及强类型的Include(导入System.Data.Entity):

from mf in context.MyForms.Include(x => x.AuditItems)
let items = from ai in mf.AuditItems
            orderby ai.DateOfAction descending
            select ai;
where items.First().Step == 1
select mf