使用实体框架刷新数据 [英] Refreshing Data Using Entity Framework

查看:95
本文介绍了使用实体框架刷新数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Entity Framework来查询数据库,并且我使用以下代码来获取一些数据。

I'm trying to use Entity Framework to query database and I have following code that I'm using to get some data.

var students= MyEntities.Students.Where(s => s.Age > 20).ToList();

此代码正常工作并返回正确的数据。但是,如果我运行这个代码,然后去数据库和更新记录来更改这个代码应该返回的数据,然后重新运行这个代码而不关闭应用程序,我得到原始数据。
我很确定它过去工作正常,但现在这不刷新数据。

This code works fine and returns correct data. However, if I run this code, then go to database and update records to change the data this code should return, and then re-run this code without shutting down the app, I'm getting original data. I'm pretty sure it used to work fine, but now this doesn't refresh data.

推荐答案

否它从未奏效这是实体框架(和许多ORM工具)的基本行为,称为身份映射(说明这里)。

No it never worked. This is essential behavior of entity framework (and many ORM tools) called identity map (explanation here).

如果您在相同的上下文中运行查询,则不会更新您的实体。它只会在运行这两个查询之间追加在数据库中创建的新实体。如果你想强制EF重新加载实体,你必须这样做:

If you run the query on the same context you will not get your entities updated. It will only append new entities created in the database between running those two queries. If you want to force EF to reload entities you must do something like this:

ObjectQuery query = MyEntities.Students;
query.MergeOption = MergeOption.OverwriteChanges;
var students = query.Where(s => s.Age > 20).ToList();

这篇关于使用实体框架刷新数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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