18
Context db = new Context();
List<Invoice> invoice =
(from LocalInvoice in db.Invoices
where LocalInvoice.Site_Id == this.SiteIdentifier
select LocalInvoice).ToList();

Returns a list of records. I want to select the last in the list. I've tried .ToList().LastOrDefault(); but the error im getting is cannot convert type 'invoice' to 'System.Collections.Generic.List.

Why is it saying this have I not declared invoice as a list List<Invoice> invoice

Any help much appreciated. Ta


EDIT Thanks for the reply everyone i've tried what you all have advised and each time im getting the error: The query operator 'LastOrDefault' is not supported.

Also I havent actually explained what I am trying to do overall which may be causing a problem. I have a table containing all the invoices, each with a seperate 'id'. However each record will have a SiteIdentifier column which is used multiple times for different invoices. So each Site may have multiple invoices.

Trying to get the most recent Invoice for the site. So say invoice

id SiteIdentifier 
73 25
74 25
75 25

I was attempting to get all the records where the SiteIdentifier == this.SiteIdentifier(e.g.25), then get the most recent record which would have beeing invoice id 75.

Anyone have any ideas? Again thanks for all the help

4

3 回答 3

29

LastOrDefault 将返回单个元素。您不应该在没有先应用过滤器的情况下调用 ToList,它会在您只需要一个时从数据库中检索所有行。

var invoice = db.Invoices.LastOrDefault(s => s.Site_Id == this.SiteIdentifier);

如果要查询关系表,还必须应用排序。LastOrDefault 仅对内存中的集合有意义。看起来它在 EF 中不受支持,并且会引发异常。

最好的解决方案是反转排序并使用 FirstOrDefault 方法:

var invoice = db.Invoices.OrderByDescending(s => s.Id) 
                         .FirstOrDefault(s => s.Site_Id == this.SiteIdentifier);
于 2013-03-27T13:20:54.830 回答
5

LastOrDefault 将返回 Invoice 的实例,而不是集合,因此请更改变量类型。

Invoice invoice =
   (from LocalInvoice in db.Invoices
    where LocalInvoice.Site_Id == this.SiteIdentifier
    select LocalInvoice).LastOrDefault();

或更清洁:

var invoice = db.Invoices.LastOrDefault(i => i.Site_Id == this.SiteIdentifier);
于 2013-03-27T13:20:49.913 回答
0

LastOrDefault将返回单个元素,而不是List. 这会起作用:

Invoice invoice =
    (from LocalInvoice in db.Invoices
     where LocalInvoice.Site_Id == this.SiteIdentifier
     select LocalInvoice)
    .LastOrDefault();
于 2013-03-27T13:20:58.633 回答