简体   繁体   English

在LinQ中实体的条件中使用最后一种方法

[英]Use Last Method in Where Condition in LinQ to Entity

look at this code 看这段代码

IQueryable<Request> RequestsTotal = DataContext.Requests;
RequestsTotal = RequestsTotal.Where(rec =>
    rec.RequestTransactions.Last().ServerStatusId != 0);

during execute this code , i occurred with an error about using Last Method in Where condition. 在执行此代码期间,发生关于在Where条件中使用Last Method的错误。 how i can solve this problem ?! 我该如何解决这个问题?

UPDATE1 : this is the occured error : UPDATE1 :这是发生的错误:

LINQ to Entities does not recognize the method 'DAL.RequestTransaction LastRequestTransaction' method, and this method cannot be translated into a store expression. LINQ to Entities无法识别方法'DAL.RequestTransaction LastRequestTransaction',并且该方法无法转换为商店表达式。

UPDATE2 : I have a Request Table , and this table has an one-to-many relation to RequestTransactions table . UPDATE2 :我有一个Request表,并且此表与RequestTransactions表具有一对多关系。 By this code I tried to fetch all requests that have not ServerStatusId = 0 on the last recode of its enter code here RequestTransactions .this there any other way ? 通过这个代码,我试图获取所有requests没有 ServerStatusId = 0在这里它的输入代码的最后重新编码RequestTransactions 。这有没有其他办法?

Try putting your Last() method outside of the where: 尝试将Last()方法放在where之外:

Request newResult =
    RequestsTotal
        .Where(rec => rec.RequestTransactions.ServerStatusId != 0)
        .Last();

Last will also execute the query and return a single Request object and not an IQueryable. 最后还将执行查询并返回单个Request对象而不是IQueryable。 So you cannot reuse 'RequestsTotal' for the result. 因此,您无法为结果重复使用“ RequestsTotal”。

I change my code to this way : 我将代码更改为这种方式:

IQueryable<Request> RequestsTotal = DataContext.Requests;
List<Request> temp = new List<Request>();
foreach (Request request in RequestsTotal)
                {

                    RequestTransaction last = request.RequestTransactions.LastOrDefault();

                    if (last != null && last.ServerStatusId != 0)
                        temp.Add(request);

                }

                RequestsTotal = temp.AsQueryable();

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

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