通过EntityFramework获取最新的表格值 [英] Get the latest Value of table via EntityFramework
问题描述
public ViewResult ShowPiece()
{
var context = new SiteContext();
var showPiece = context.Portraits.LastOrDefault();
return View(showPiece);
}
但是当我运行应用程序并浏览以上操作时,我遇到了错误:
LINQ to Entities不识别该方法,并且此方法无法转换为存储表达式...
这是什么问题?
使用降序(按日期或id)和 FirstOrDefault
这是支持的:
var showPiece = context.Portraits
.OrderByDescending(p => p.Date)
.FirstOrDefault ();
另一个选项是选择最大日期的肖像(id)通过子查询(如Evelie在评论中提出的):
var showPiece = context.Portraits
.FirstOrDefault p => p.Date == context.Portraits.Max(x => x.Date));
我在这里做了一些调查。在第一种情况下(顺序)生成以下查询:
SELECT TOP(1)[t0]。*
FROM [肖像] AS [t0]
ORDER BY [t0]。[日期] DESC
在第二种情况下(获得最大值):
SELECT TOP(1)[t0]。*
FROM [Portraits] AS [t0]
WHERE [t0]。[Date] =((
SELECT MAX([t1]。[Date])
FROM [Portraits] AS [t1]
))
执行计划几乎相同,但在第二种情况下,Top被执行两次。因此,与索引扫描相比,顶部成本为0%,这不应该是一个问题。
I have a table that have several field and each of them update separately by separate ViewModel , Now I wanna to get the latest Value of a specific field (maybe it has updated in fifth record of my table) , OK? now what I have write is look like this :
public ViewResult ShowPiece()
{
var context = new SiteContext();
var showPiece = context.Portraits.LastOrDefault();
return View(showPiece);
}
but when I run the application and navigate above action , I got thie Error :
LINQ to Entities does not recognize the method , and this method cannot be translated into a store expression...
what is the problem with that ??
Use descending ordering (by date, or id) and FirstOrDefault
which is supported:
var showPiece = context.Portraits
.OrderByDescending(p => p.Date)
.FirstOrDefault();
Another option, is select portrait which has max date (id) via subquery (as Evelie suggested in comments):
var showPiece = context.Portraits
.FirstOrDefault(p => p.Date == context.Portraits.Max(x => x.Date));
I made a little investigation here. In first case (ordering) following query is generated:
SELECT TOP (1) [t0].*
FROM [Portraits] AS [t0]
ORDER BY [t0].[Date] DESC
In second case (getting max):
SELECT TOP (1) [t0].*
FROM [Portraits] AS [t0]
WHERE [t0].[Date] = ((
SELECT MAX([t1].[Date])
FROM [Portraits] AS [t1]
))
Execution plan is almost same, but in second case Top is executed twice. Thus Top costs 0% comparing to Index Scan, this should not be a problem.
这篇关于通过EntityFramework获取最新的表格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!