简体   繁体   中英

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. how i can solve this problem ?!

UPDATE1 : this is the occured error :

LINQ to Entities does not recognize the method 'DAL.RequestTransaction LastRequestTransaction' method, and this method cannot be translated into a store expression.

UPDATE2 : I have a Request Table , and this table has an one-to-many relation to RequestTransactions table . 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 ?

Try putting your Last() method outside of the 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. So you cannot reuse 'RequestsTotal' for the result.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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