通过EntityFramework获取最新的表格值 [英] Get the latest Value of table via EntityFramework

查看:136
本文介绍了通过EntityFramework获取最新的表格值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表格有几个字段,每个表单由ViewModel单独更新,现在我想获取一个特定字段的最新值(也许它已经在我的表的第五条记录中更新),OK?现在我写的是这样的:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆